HTML Canvas 水平翻转仅在每秒单击一次时有效
我有一个画布元素,上面加载了一张照片。单击链接时,将执行以下操作:
var ctx = canvas.getContext("2d");
ctx.scale(-1,1);
ctx.drawImage(canvas, canvas.width * -1, 0, canvas.width, canvas.height);
在第一次单击、第三次单击、第五次单击等时按预期工作(图像水平翻转)。在第二次单击、第四次单击、第六次单击等时,什么也没有发生。
关于如何让它适用于每次点击,有什么想法吗?
I have a canvas element with a photo loaded on it. When clicking a link, the following is performed:
var ctx = canvas.getContext("2d");
ctx.scale(-1,1);
ctx.drawImage(canvas, canvas.width * -1, 0, canvas.width, canvas.height);
This works as expected (the image is flipped horizontally) on the first click, the third click, the fifth click, etc. On the second click, the fourth click, the sixth click, etc, nothing happens.
Any ideas on how I can get this to work for every click?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,问题是因为你在绘制图像后没有将画布比例恢复到 1,1,所以基本上第一次调用事件时你的画布比例将在下次调用时变成 -1,1为 1,1 但您需要它始终为 -1,1。这是因为您直接从画布而不是图像元素绘制图像,因此每次都需要翻转它。
尝试在缩放之前使用 ctx.save() 并在绘制图像之后使用 ctx.restore() 。或者在绘制图像后再次调用 ctx.scale(-1, 1) 。或者,如果您的画布仅用于此目的,您可以在事件之外进行缩放(但在第一次将图像绘制到画布之后)。
Yeah, the problem is because you're not restoring the canvas scale to 1,1 after you draw the image, so basically the first time the event is called your canvas scale is gonna be turned into -1,1 the next time it's gonna be 1,1 but you need it to be always -1,1. That's because you're drawing the image directly from the canvas and not from an image element thus, you gonna need to flip it every time.
Try using
ctx.save()
before the scaling andctx.restore()
after drawing the image. Or callingctx.scale(-1, 1)
again after drawing the image. Or you could just do the scaling outside the event (but after you've drawn the image to the canvas the first time) if your canvas is only used for this.这适用于每次点击:
http://jsfiddle.net/4kcjn/2/
问问自己,它和你的有什么不同?
它可能与图像加载相关。尝试一下没有图像的情况。是否还存在同样的问题?
This here works for every click:
http://jsfiddle.net/4kcjn/2/
Ask yourself, what is different between it and yours?
It could be image-load related. Try yours without an image. Does it still have the same problem?