---
url: /examples/textures/image.md
description: >-
  Load an image texture asynchronously and swap it in after rendering an initial
  placeholder texture.
---

::: example-editor

```ts
import { glCanvas, loadTexture, TextureParams } from "@radiancejs/gl";
import "./styles.css";
import fragment from "./fragment.glsl?raw";
import vertex from "./vertex.glsl?raw";

const { uniforms } = glCanvas({
  canvas: "#glCanvas",
  vertex,
  fragment,
  uniforms: {
    uResolution: ({ canvasResolution }) => canvasResolution,
    // placeholder texture. You can use another lighter image
    uTexture: {
      data: new Uint8Array(
        [
          [255, 255, 255, 255],
          [255, 255, 255, 255],
          [255, 255, 255, 255],
          [255, 255, 255, 255],
          [99, 46, 22, 255],
          [255, 255, 255, 255],
        ].flat(),
      ),
      width: 3,
      height: 2,
    } as TextureParams,
  },
});

loadTexture("https://picsum.photos/id/669/600/400").then((texture) => {
  setTimeout(() => {
    uniforms.uTexture = texture;
  }, 300);
});

```

```glsl
/**
* This is an example of implementation of the `object-fit: contain/cover` CSS property.
* It would be much simpler to give the canvas the size of the image.
*/

attribute vec2 position;
attribute vec2 uv;
uniform sampler2D uTexture;
uniform vec2 uResolution;
varying vec2 vUv;

#define CONTAIN 1
#define COVER 2
#define OBJECT_FIT CONTAIN

void main() {
  vec2 textureResolution = vec2(textureSize(uTexture, 0));
  float canvasRatio = uResolution.x / uResolution.y;
  float textureRatio = textureResolution.x / textureResolution.y;

  vUv = position;
  if(OBJECT_FIT == CONTAIN ? canvasRatio > textureRatio : canvasRatio < textureRatio) {
    vUv.x *= canvasRatio / textureRatio;
  } else {
    vUv.y *= textureRatio / canvasRatio;
  }
  vUv = (vUv + 1.0) / 2.0;
  gl_Position = vec4(position, 0.0, 1.0);
}

```

```glsl
varying vec2 vUv;
uniform sampler2D uTexture;

void main() {
  vec3 color = texture(uTexture, vUv).rgb;
  color *= step(0., vUv.x) * (1. - step(1., vUv.x));
  color *= step(0., vUv.y) * (1. - step(1., vUv.y));

  gl_FragColor = vec4(color, 1.);
}

```

```css
html {
  color-scheme: light dark;
}

body {
  margin: 0;
}

canvas {
  width: 100svw;
  height: 100svh;
  display: block;
}

```

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>RadianceJS Example</title>
  </head>
  <body>
    <canvas id="glCanvas"></canvas>
    <script src="/index.ts"></script>
  </body>
</html>

```

:::
