Javascript Scale(x,y)方法没有't在Canvas上使用负参数

Javascript Scale(x,y) method doesn't work on Canvas with negative parameter

本文关键字:Canvas 参数 Scale 方法 Javascript      更新时间:2023-09-26

我正在尝试使用scale()方法翻转图像。我有这个代码:

ctx.save();
ctx.scale(-1, 1);
ctx.drawImage(Img, 0, 0, 100, 100);
ctx.restore();

当我在比例参数或任何其他实数中输入1,1时,比例函数工作正常。但一旦我设置了一个负参数,比如-1(水平翻转图像),图像就根本画不出来了。该代码位于一个setInterval为12 fps的函数中。我到处找了,但似乎找不到解决办法。如有任何帮助或建议,我们将不胜感激。谢谢

正如markE所说,无论何时缩放、旋转或变换画布,您使用的坐标都会对画布变换的变化做出反应——在您的情况下,会将图像从画布上发送出去。为了将图像翻转到位,您应该考虑使用将图像宽度作为第一个参数的平移:

ctx.save();
//The scale will flip the whole canvas, and will move the image 
//to the left (by the image width size)
ctx.scale(-1, 1);
//Using translate to move the image back to it's original origin
ctx.translate(Img.width, 0)
ctx.drawImage(Img, 0, 0, 100, 100);
ctx.restore();