HTML5 canvas, scale image after drawing it

核能气质少年 提交于 2019-12-06 22:01:02

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/13903257/html5-canvas-scale-image-after-drawing-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!