简体   繁体   English

HTML Canvas-JavaScript动态轮换问题

[英]HTML Canvas - JavaScript dynamic rotation issue

I am trying to make a simple game with HTML Canvas and JavaScript but I am running into a unique issue. 我正在尝试使用HTML Canvas和JavaScript制作一个简单的游戏,但遇到了一个独特的问题。 My code is incomplete and perhaps I am missing something obvious, but essentially I am trying to apply a fluctuating rotate transformation to a lightsaber image that follows the position of the mouse. 我的代码不完整,也许我遗漏了一些明显的东西,但实际上,我试图对跟随鼠标位置的光剑图像应用波动的旋转变换。 The problem is it seems moving my canvas diagonally at the same time as applying the rotation leaves pieces of the old frames left behind. 问题是似乎在对角移动我的画布的同时应用旋转会留下一些旧框架。

The essential idea is that this will be called continuously upon registration of a "mousemove" event: 基本思想是在“ mousemove”事件注册后将连续调用此方法:

ctx.clearRect(0, 0, w, h);
ctx.translate(ax, ay);
ctx.rotate(Math.PI/180);
// Draw image back
ctx.translate(-ax, -ay);
ctx.drawImage(saberimg, x-90, y-438);

To illustrate: https://jsfiddle.net/2ynfq5k0/ 进行说明: https : //jsfiddle.net/2ynfq5k0/

Update: click the right mouse button to rotate right, and the mouse wheel to rotate left. 更新:单击鼠标右键向右旋转,单击鼠标滚轮向左旋转。

You aren't resetting the canvas state, so your clearRect is still operating under the rotation, resulting in it not actually clearing the canvas. 您没有重置画布状态,因此您的clearRect仍在旋转下运行,导致它实际上并未清除画布。

As a general rule, if you're working with transformations ( translate , rotate , ...) then you should always put ctx.save() before, and ctx.restore() after. 作为一般规则,如果你使用的转换工作( translaterotate ,...),那么你应该始终ctx.save()之前,和ctx.restore()之后。 This saves and restores the canvas' state with regard to transformations and styles. 这样可以保存和恢复画布在转换和样式方面的状态。 This is great for bigger projects, where you want to be sure that code in one place doesn't interfere with code elsewhere, and is basically the canvas equivalent to "not polluting the global scope". 这对于较大的项目非常有用,您需要确保一个地方的代码不会干扰其他地方的代码,并且基本上是等同于“不污染全局范围”的画布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM