Search code examples
javascripthtml5-canvas

Layering an image on top of an HTML canvas that already has an image as its background


I created a canvas element with a colored background, and I came up with the following code to insert an image on top of this canvas:

    const canvas = document.getElementById(id);
    console.log(canvas);
    if (canvas.getContext) {
        var context = canvas.getContext('2d');
        var img = new Image();
        img.src = 'https://google.com/xyz.jpg';
        img.onload = function () {
            context.save();
            context.rect(10, 2, 10, 10);
            context.clip();
            context.drawImage(img, 0, 0); // image won't resize 
            context.restore();
        };
    }

Now this successfully layers the image on top of the canvas (it's cut off however), but I can't find a way to resize the image to be of a certain size (for example 10x10). I tried changing changing the second last line in my code to context.drawImage(img, 0, 0, 10, 10); but this broke my code and the image would not display on the canvas at this point. Any help would be greatly appreciated!

Image of my canvas for reference:


Solution

  • To load and draw an image.

    const ctx = can.getContext('2d');
    const img = new Image;        
    img.src = 'https://pbs.twimg.com/media/DyhGubJX0AYjCkn.jpg';
    img.addEventListener("load", () => {
        // draw image at 10, 10, width and height 50,50
        ctx.drawImage(img, 10, 10, 50, 50);  // resizes image
    }, {once: true});
        
    canvas {
       background: green;
    }
    <canvas id="can" width="200" height = "200"></canvas>