【发布时间】:2015-05-28 00:57:43
【问题描述】:
我使用 HTML5 画布元素在 Web 应用程序中显示图像,我想水平翻转图像而不对画布应用缩放变换。这意味着我不想为此使用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:要绘制到目标上下文中的源图像的子矩形的宽度。如果未指定,则使用从 sx 和 sy 指定的坐标到图像右下角的整个矩形。 如果指定负值,则在绘制时图像会水平翻转。
这就是我绘制图像的方式:
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:索引或大小为负数或大于允许的值 金额
我不明白我在这里做错了什么。如何在不缩放画布的情况下水平翻转图像?
【问题讨论】:
-
我第一次使用
scale()和restore()测试时犯了一个错误。这实际上工作正常。 -
我更新了
drawImage()的 Mozilla 页面,因为规范中没有提到使用负值翻转图像。