html - 如何在不缩放的情况下使用 HTML5 canvas 翻转图像

标签 html canvas drawimage

我使用 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);

这里的工作示例:https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage#Using_the_drawImage_method

但是如果我尝试按照描述翻转图像,我会在 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/

相关文章:

html - CSS 属性旁边的星号是什么意思?

html - 动态响应调整图像大小

c# - 如何在不缩放主摄像头的情况下为移动设备创建可缩放的 Canvas 图像?

javascript - Canvas 动画循环

javascript - 在 Iphone Web 应用程序上使用 canvas drawImage() 函数

c# - Graphics.DrawImage() 在使用 RotateTransform() 时剪辑图像

html - 不能在媒体查询中使用列数

javascript - 如何设计自定义文件上传按钮,以便标签在文件上传时发生变化

java - 代码无法正确重绘

javascript - drawimage 后 Canvas 中的图像立即消失