如何旋转画布中的一张图像?
我正在制作一个 HTML5 画布游戏,我希望旋转其中一张图像。
var link = new Image();
link.src='img/link.png';
link.onload=function(){
ctx.drawImage(link,x,y,20,20); // draws a chain link or dagger
}
我想旋转这个图像。旋转图像的标准方法是在画布上下文对象上设置旋转。然而,这改变了整个游戏!我不想这样做,只想旋转这个精灵。我该怎么做?
I am making an HTML5 canvas game, and I wish to rotate one of the images.
var link = new Image();
link.src='img/link.png';
link.onload=function(){
ctx.drawImage(link,x,y,20,20); // draws a chain link or dagger
}
I wish to rotate this image. The standard way of rotating image was to set a rotation on the canvas context object. However, that rotates the entire game! I don't want to do that, and only wish to rotate this one sprite. How do I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用
.save()
和.restore()
(更多信息):Use
.save()
and.restore()
(more information):您可能需要在此处放置一个
translate();
,因为图像将围绕原点旋转,并且默认情况下位于左上角,因此您可以使用translate();< /code> 更改原点。
You might want to put a
translate();
there because the image is going to rotate around the origin and that is in the top left corner by default so you use thetranslate();
to change the origin.您最初的“解决方案”是:
但是,通过使用以下代码可以提高效率(无需
保存
或恢复
):Your original "solution" was:
However, it can be made more efficient (with no
save
orrestore
) by using this code:看看我的解决方案。这是完整的示例,也是最容易理解的。
Look at my solution. It's full example and the easiest to understand.
在这里,我从我的一款游戏中制作了一个工作示例。您可以从此处获取图像。
Here i made a working example from one of my games. u can get the image from Here.
我最终不得不做:
I ended up having to do: