Search code examples
imagehtmlcanvasscale

HTML5 canvas, scale image after drawing it


I'm trying to scale an image that has already been draw into canvas. This is the code:

var canvas = document.getElementById('splash-container');
var context = canvas.getContext('2d');
var imageObj = new Image();

imageObj.onload = function() {
  // draw image at its original size
  context.drawImage(imageObj, 0, 0);
};
imageObj.src = 'images/mine.jpeg';

// Now let's scale the image.
// something like...
imageObj.scale(0.3, 0.3);

How should I do?


Solution

  • You're thinking about it wrong. Once you've drawn the image onto the canvas it has no relationship to the imageObj object. Nothing you do to imageObj will affect what's already drawn. If you want to scale the image, do in the drawImage function:

    drawImage(imgObj, 0, 0, imgObj.width * 0.3, imgObj.height * 0.3)
    

    If you want to animate the scaling or are looking to achieve some other effect which requires you to draw the image at full size initially you'll have to first clear it before drawing the scaled down image.