HTML5画布,绘制后缩放图像 [英] 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);
我应该怎么做?
推荐答案
您正在考虑错误。将图像绘制到画布
之后,它与 imageObj
对象没有关系。您对 imageObj
所做的任何操作都不会影响已经绘制的内容。如果要缩放图像,请在 drawImage
函数:
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.
这篇关于HTML5画布,绘制后缩放图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!