Home ยป HTML Canvas Adding Images Tutorial

HTML Canvas Adding Images Tutorial

by shedders

The HTML5 <canvas> element allows you to draw and manipulate images dynamically using the CanvasRenderingContext2D API.

You can use images as backgrounds, manipulate them pixel by pixel, or combine them with other elements like shapes and text.

In this tutorial, you’ll learn:

  1. How to draw images on a canvas.
  2. Resizing and cropping images.
  3. Combining images with transformations.
  4. Manipulating image pixels.
  5. Practical examples using canvas images.

1. Drawing Basic Images

To draw an image, you use the drawImage() method.

Syntax:

ctx.drawImage(image, dx, dy);
  • image: The image to draw.
  • dx, dy: The coordinates where the image will be placed.

Example 1: Drawing an 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 image at (50, 50)
    };
</script>

2. Resizing Images

You can scale images dynamically using additional width and height parameters.

Syntax:

ctx.drawImage(image, dx, dy, dWidth, dHeight);
  • dWidth, dHeight: The width and height of the image on the canvas.

Example 2: Resizing an Image

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

3. Cropping Images

You can crop a portion of the source image and draw it on the canvas.

Syntax:

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

Example 3: Cropping an Image

img.onload = () => {
    // Crop the center of the image
    ctx.drawImage(img, 50, 50, 50, 50, 200, 50, 100, 100); // Crop and scale to 100x100
};

4. Combining Images with Transformations

You can apply transformations like scaling, rotating, and translating to images.

Example 4: Rotating an Image

img.onload = () => {
    ctx.save(); // Save the current state
    ctx.translate(200, 150); // Move the origin to the image's center
    ctx.rotate(Math.PI / 4); // Rotate 45 degrees
    ctx.drawImage(img, -75, -75, 150, 150); // Draw rotated image
    ctx.restore(); // Restore the original state
};

Explanation:

  • save() and restore(): Preserve the context state to avoid affecting other drawings.

5. Manipulating Image Pixels

The getImageData() method lets you access and manipulate individual pixels.

Syntax:

const imageData = ctx.getImageData(sx, sy, sw, sh);
  • sx, sy: Starting coordinates of the area.
  • sw, sh: Width and height of the area.

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. Combining Images with Shapes and Text

You can overlay text or draw shapes over images to create compositions.

Example 6: Adding Text Over an Image

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

    // Add text
    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);
};

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);

        // Draw once all images are loaded
        if (loadedImages === images.length) {
            ctx.font = "20px Arial";
            ctx.fillStyle = "black";
            ctx.fillText("Collage Complete!", 50, 200);
        }
    };
});

8. Best Practices for Canvas Images

  1. Wait for Images to Load:
    • Always use the onload event to ensure the image is fully loaded before drawing.
  2. Optimize Image Size:
    • Use appropriately sized images for better performance.
  3. Combine Transformations:
    • Apply scaling and rotation to create dynamic effects.
  4. Preserve State:
    • Use save() and restore() to avoid unwanted transformations.

9. Browser Support

All modern browsers support canvas image methods:

Feature Supported?
drawImage Yes
getImageData Yes
putImageData Yes
rotate, scale Yes

10. Conclusion

In this tutorial, you learned:

  1. How to draw images on a canvas.
  2. How to resize, crop, and transform images.
  3. How to manipulate image pixels for custom effects.
  4. Practical applications like text overlays and collages.

You may also like