Home ยป HTML Canvas Working with Images Tutorial

HTML Canvas Working with Images Tutorial

by shedders

The HTML5 <canvas> element allows you to draw, manipulate, and animate images on the canvas.

The CanvasRenderingContext2D API provides methods to load, scale, crop, and combine images dynamically.

1. Drawing an Image

The drawImage() method is used to draw images on the canvas.

Syntax:

ctx.drawImage(image, dx, dy);
  • image: The image object (e.g., HTMLImageElement or HTMLCanvasElement).
  • dx, dy: The coordinates where the image will be drawn.

Example 1: Drawing a Basic Image

<canvas id="myCanvas" width="500" height="300" style="border: 1px solid black;"></canvas>
<script>
    const canvas = document.getElementById("myCanvas");
    const ctx = canvas.getContext("2d");

    const img = new Image();
    img.src = "https://via.placeholder.com/150"; // Example image URL
    img.onload = () => {
        ctx.drawImage(img, 50, 50); // Draw the image at (50, 50)
    };
</script>

2. Resizing Images

You can resize images dynamically by specifying width and height.

Syntax:

ctx.drawImage(image, dx, dy, dWidth, dHeight);
  • dWidth, dHeight: The width and height to draw the image.

Example 2: Resizing an Image

img.onload = () => {
    ctx.drawImage(img, 50, 50, 100, 100); // Resize to 100x100
};

3. Cropping Images

You can crop a section of the image before drawing it on the canvas.

Syntax:

ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
  • sx, sy: Starting point of the crop on the source image.
  • sWidth, sHeight: Dimensions of the crop.
  • dx, dy: Where to place the cropped section on the canvas.
  • dWidth, dHeight: Dimensions of the cropped image on the canvas.

Example 3: Cropping an Image

img.onload = () => {
    // Crop a 50x50 area starting from (25, 25) on the source image
    ctx.drawImage(img, 25, 25, 50, 50, 100, 100, 150, 150); // Scale to 150x150
};

4. Combining Images with Other Elements

You can overlay text, shapes, or other images on top of an image.

Example 4: Adding Text Over an Image

img.onload = () => {
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

    // Add text overlay
    ctx.font = "30px Arial";
    ctx.fillStyle = "white";
    ctx.strokeStyle = "black";
    ctx.lineWidth = 2;
    ctx.strokeText("Canvas Text", 20, 50);
    ctx.fillText("Canvas Text", 20, 50);
};

5. Manipulating Image Pixels

The getImageData() method allows you to access and manipulate individual pixels of an image.

Syntax:

const imageData = ctx.getImageData(sx, sy, sw, sh);
  • imageData.data: Contains an array of RGBA values for each pixel.

Example 5: Grayscale Filter

img.onload = () => {
    ctx.drawImage(img, 0, 0, 300, 200);

    // Get image data
    const imageData = ctx.getImageData(0, 0, 300, 200);
    const pixels = imageData.data;

    // Convert to grayscale
    for (let i = 0; i < pixels.length; i += 4) {
        const r = pixels[i];
        const g = pixels[i + 1];
        const b = pixels[i + 2];
        const gray = 0.3 * r + 0.59 * g + 0.11 * b;
        pixels[i] = pixels[i + 1] = pixels[i + 2] = gray; // Set RGB to grayscale
    }

    // Put image data back
    ctx.putImageData(imageData, 0, 0);
};

6. Animating Images

You can animate images by repeatedly clearing and redrawing them with different positions or sizes.

Example 6: Moving an Image

let x = 0;

function animateImage() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.drawImage(img, x, 50, 100, 100); // Draw the image
    x += 2; // Move the image to the right

    if (x > canvas.width) {
        x = -100; // Reset position when it goes off-screen
    }

    requestAnimationFrame(animateImage);
}

img.onload = () => {
    animateImage();
};

7. Practical Example: Image Collage

Example 7: Creating an Image Collage

const images = [
    "https://via.placeholder.com/100",
    "https://via.placeholder.com/120",
    "https://via.placeholder.com/80"
];

let loadedImages = 0;
images.forEach((src, index) => {
    const img = new Image();
    img.src = src;
    img.onload = () => {
        loadedImages++;
        ctx.drawImage(img, 50 + index * 120, 50, 100, 100);

        // Add a label to each image
        ctx.font = "16px Arial";
        ctx.fillStyle = "black";
        ctx.fillText(`Image ${index + 1}`, 50 + index * 120, 170);
    };
});

8. Best Practices for Using Images in Canvas

  1. Wait for Images to Load:
    • Always use the onload event to ensure the image is fully loaded before drawing it.
  2. Optimize Image Size:
    • Use appropriately sized images to improve performance.
  3. Clear Before Redrawing:
    • Use clearRect() before drawing updated frames to avoid overlapping visuals.
  4. Cache Repeated Operations:
    • Cache image data or reuse images when possible to minimize reloading.

9. Browser Support

All modern browsers support the Canvas image methods:

Feature Supported?
drawImage Yes
getImageData Yes
putImageData Yes
requestAnimationFrame Yes

10. Conclusion

In this tutorial, you learned:

  1. How to draw, resize, and crop images on a canvas.
  2. How to overlay text and manipulate image pixels.
  3. How to animate and combine images dynamically.

You may also like