简体   繁体   中英

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. 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:

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/

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.

As a general rule, if you're working with transformations ( translate , rotate , ...) then you should always put ctx.save() before, and ctx.restore() after. 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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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