我使用 HTML5 canvas 元素在 Web 应用程序中显示图像,我想水平翻转图像, 不对 Canvas 应用缩放转换。这意味着我不想使用 CanvasRenderingContext2D.scale()为此目的,因为我不想翻转其他任何东西。
// I don't want this, because it breaks the rest of the application. I have
// implemented zooming and landmark placement functionality, which no longer
// work properly after scaling.
ctx.save();
ctx.scale(-1, 1);
ctx.drawImage(image, -image.width, 0, image.width, image.height);
ctx.restore();
在我看来,我应该能够用 CanvasRenderingContext2D.drawImage() 做到这一点方法,因为该页面显示:
sWidth: The width of the sub-rectangle of the source image to draw into the destination context. If not specified, the entire rectangle from the coordinates specified by sx and sy to the bottom-right corner of the image is used. If you specify a negative value, the image is flipped horizontally when drawn.
这是我绘制图像的方式:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var image = document.getElementById('source');
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, image.width, image.height);
但是如果我尝试按照描述翻转图像,我会在 Firefox 中收到以下错误:
ctx.drawImage(image, 0, 0, -image.width, image.height, 0, 0, image.width, image.height);
IndexSizeError: Index or size is negative or greater than the allowed amount
我不明白我在这里做错了什么。如何在不缩放 Canvas 的情况下水平翻转图像?
最佳答案
一个相当简单的解决方案是使用第二个 Canvas ,只在其中绘制翻转一次的图像,然后将另一个 Canvas 的该部分绘制到主 Canvas 上。这将成功创建图像的翻转版本,缓存,你可以在任何你想画的地方画它。
关于html - 如何在不缩放的情况下使用 HTML5 canvas 翻转图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29237305/