HTML5 canvas, scale image after drawing it

2019-04-23 16:04发布

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?

2条回答
姐就是有狂的资本
2楼-- · 2019-04-23 16:23

What robertc says is correct, but if you really wanted to scale an image on a canvas after drawing it for some reason, you could just scale the whole canvas using the CSS width/height properties and that would scale the image without having to redraw it.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-04-23 16:31

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.

查看更多
登录 后发表回答