+ 2
How to change canvas rotation of an item (not the whole canvas)
Currently, rotation an item moves it wildly across the screen. I want the item to stay in place while it rotates (saying on the same x and y axis but rotating) independent from the canvas. How do I do this?
2 Respuestas
+ 3
Here is a working example of rotating around an arbitrary point.
Copy this and make it work for your stuff. Share your code in Sololearn's Code Playground if you get stuck.
After calling translate and rotate, drawing anything will end up translated(moved) and rotated. This combination is key to rotating around arbitrary points.
Make sure you have a canvas element with id="myCanvas". I wish I could share all the HTML tags but Sololearn's answer feature is broken for submitting HTML.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
function update() {
ctx.clearRect(0, 0, 1000, 1000);
var newT = new Date().getTime();
var angle = (newT * 0.01) % (Math.PI * 2);
ctx.save(); // remember transformation matrix before updating it.
ctx.translate( 100, 100 );
ctx.rotate(angle);
ctx.fillRect(-50, -20, 100, 40);
ctx.restore(); // restore transformation matrix.
requestAnimationFrame(update);
}
update();
+ 1
I will give it a try, thank you very much!
Yup it works! Thank you!