How to change the origin of the canvas to the center?

I'm new to html and JavaScript, I am writing a program dealing with points and lines in a coordinate system, but as you know the origin of a canvas for html5 is at the upper corner, I want to build a coordinate system with its origin at the center of the canvas, I have tried the translate method and use the following method to print where my mouse is (ideally, I want it to display 0 : 0 when the mouse is at the center of the canvas), but it does not seem to work:

var mousePos = getMousePos(canvas1, evt); mouseX = mousePos.x; mouseY = mousePos.y; var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y; writeMessage(document.getElementById("canvas_prime_coor"), message); function writeMessage(canvas, message) { var context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); context.font = '18pt Calibri'; context.fillStyle = 'red'; context.fillText(message, 10, 25); } function getMousePos(canvas, evt) { var rect = canvas.getBoundingClientRect(); return { x: evt.clientX - rect.left, y: evt.clientY - rect.top}; }

Answer1:

To change the coordinate system you can use the translate() method. However, transformation of the context does not affect the mouse coordinates which are bounded to the element itself so you need to keep track of this separately.

You will have to manually track the translation and compensate for the mouse coordinates:

var transX = canvas.width * 0.5, transY = canvas.height * 0.5; context.translate(transX, transY);

The problem now is that you deal with two different positions:

a) The actual mouse position relative to element b) The coordinate needed to be correct for the context

If you translate and then use the mouse position, and you translate to center the following would happen:

Lets say your mouse coordinate was 30,30. If you use this coordinate on a translated context the graphics would end up at transX + 30, transY + 30 which is not what you want.

To compensate for this you need to keep track of current translation and subtract that to the mouse coordinates:

function getMousePos(canvas, evt) { var rect = canvas.getBoundingClientRect(); return { x: evt.clientX - rect.left - transX, y: evt.clientY - rect.top - transY }; }

<strong>FIDDLE</strong>

Hope this helps!

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:How to change the origin of the canvas to the center?