jar4563 Posted July 11, 2020 Share Posted July 11, 2020 (edited) Hi I have been trying to figure out why javascript image rotation wont work. I'm testing the rotation demo in w3schools.com site but even that does not work. The more angle you put to the image the further it goes off from the screen. When it's supposed to rotate the rect from the middle the rect seems to orient 0,0 Here's link to the tutorial: https://www.w3schools.com/tags/canvas_rotate.asp Oh and that tutorial uses rect drawing but it's the same issued with drawImage() Any ideas why it doesn't work? I use google chrome thx! Edited July 11, 2020 by jar4563 Quote Link to comment Share on other sites More sharing options...
grelf Posted July 11, 2020 Share Posted July 11, 2020 The rotation will always be about the origin (0, 0). If you want to rotate about the centre of an object you must first translate the centre to the origin, do the rotation and translate back again. Javascript rotation certainly does work. I don't find the w3schools site very good - incomplete and not fully up to date. I use Mozilla's site for reference and the occasional tutorial. They cover rotation very clearly on this page: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Transformations Mozilla is good for finding out which browsers support newer features too. Quote Link to comment Share on other sites More sharing options...
jar4563 Posted July 11, 2020 Author Share Posted July 11, 2020 (edited) @grelf Thanks for the link following the rotation example on that page I have this code now: ctx.save(); // right rectangles, rotate from rectangle center // draw blue rect ctx.fillStyle = '#0095DD'; ctx.fillRect(150, 30, 100, 100); ctx.translate(200, 80); // translate to rectangle center // x = x + 0.5 * width // y = y + 0.5 * height ctx.rotate((Math.PI / 180) * rotAngle); // rotate ctx.translate(-200, -80); // translate back ctx.restore(); // Draw some text: ctx.font = "30px Arial"; ctx.fillText("Pos: " + worldPos.x + " " + worldPos.y, 5, gameArea.canvas.height - 15); But nothing happens. only if I remove the save() and restore() the rect rotates as supposed to but then it also rotates the text's position that I'm also drawing What am I doing wrong? Edited July 11, 2020 by jar4563 Quote Link to comment Share on other sites More sharing options...
jar4563 Posted July 11, 2020 Author Share Posted July 11, 2020 nvm that code was really bad, got it working Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.