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

后端 未结 1 1798
鱼传尺愫
鱼传尺愫 2021-01-19 12:41

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 uppe

1条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-19 13:18

    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
        };
    }
    

    FIDDLE

    Hope this helps!

    0 讨论(0)
提交回复
热议问题