Html HTML5 画布,绘制后缩放图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13903257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:24:22  来源:igfitidea点击:

HTML5 canvas, scale image after drawing it

imagehtmlcanvasscale

提问by Mich Dart

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?

我应该怎么做?

回答by robertc

You're thinking about it wrong. Once you've drawn the image onto the canvasit has no relationship to the imageObjobject. Nothing you do to imageObjwill affect what's already drawn. If you want to scale the image, do in the drawImagefunction:

你想错了。将图像绘制到 上后,canvas它与imageObj对象没有任何关系。您所做的任何事情都imageObj不会影响已经绘制的内容。如果要缩放图像,请在drawImage函数中执行

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 itbefore drawing the scaled down image.

如果您想为缩放设置动画或希望获得一些其他效果,这需要您最初以全尺寸绘制图像,则必须在绘制缩小图像之前先清除它

回答by hobberwickey

What robertc says is correct, but if you really wanted to scale an image on a canvas afterdrawing 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.

robertc 说的是正确的,但是如果您出于某种原因真的想在画布上缩放图像,您可以使用 CSS 宽度/高度属性缩放整个画布,这样就可以缩放图像而无需重新绘制它.