Home > Back-end >  canvas.rotate not working properly for me
canvas.rotate not working properly for me

Time:10-04

I am in the process of making an arrow that points to an end goal using a canvas in HTML5 and Javascript. I am doing this by finding the x and y coordinates of the player and the end goal, then using Math.atan2() to find the angle. Up to that point everything works flawlessly, but then I get to the point of rendering the arrow at the same angle of the two points. I use ctx.translate() and ctx.rotate() to rotate the canvas accordingly, but it seems like the canvas doesn't rotate the same amount of degrees as I tell it to. For example:

var angles = 90;
ctx.rotate(angles);

but the canvas will rotate MUCH further than I want it to. Any clues as to why the canvas doesnt rotate by degrees and how to fix this? If needed here is the link to my game WIP: https://jsfiddle.net/juinorCPC/0azfu2wp/4/

EDIT: I should probably also mention that i HAVE tried to rotate by radians and not by degrees, but the issue is that when i use radians, the canvas will rotate much LESS than it is supposed to.

EDIT x2: I fixed the jsfiddle.

A quick example of the problem im seeing in action for those who cant get the fiddle to work:

Lets say I have a player in the middle of the canvas: (250, 250). I have a goal at another part of the canvas: (325, 125). I get the rotation in degrees: 23.96248897457819. Now i use ctx.rotate (better known as canvas.rotate() ) to rotate the canvas around the mid point (250, 250). The canvas does NOT rotate how i would like it to. IF i use degrees it rotates too much, if i use radians, it rotates too little.

CodePudding user response:

Hola it me again try using this and if it work it work

function angle(playerX, playerY, goalX, goalY) {
        var dx = playerX - goalX;
        var dy = playerY - goalY;
        var theta = Math.atan2(-dy, -dx);
        theta *= 180 / Math.PI;
        
        return theta;
    }
  • Related