Set canvas origin to the lower-left corner

后端 未结 3 967
执念已碎
执念已碎 2021-02-05 23:40

Is there a way to set the origin to lower-left of the canvas? I tried scaling by −1 but after that everything is upside down. I need to make something like a coordinate sy

相关标签:
3条回答
  • 2021-02-05 23:57
    ctx.translate(0, canvas.height);
    ctx.scale(1, -1);
    

    See a demo on JSFiddle.

    0 讨论(0)
  • 2021-02-05 23:57

    is there a way to set the origin to lower-left of the canvas?

    Not quite the way you'd like, no. The best you can do there is what icktoofay said.

    That being said it isn't too hard to make a function to convert between one system and the other. For example:

    // Given an X,Y in 1st quadrant cartesian coordinates give the corresponding screen coordinate
    function cartToScreen(px, py) {
      return [px, -py + HEIGHT];
    };
    

    So you'd write:

    var coords = cartToScreen(50,50);
    // draws 50 pixels from the bottoom instead of 50 pixels from the top
    ctx.fillText("lalala", coords[0], coords[1]);
    

    Example

    In any case, I'd strongly suggest that if you are at all able to just get used to screen coordinates. It will save you from loads of headaches in the future if you don't always have to account for this little difference.

    0 讨论(0)
  • 2021-02-06 00:05

    One of the easiest and correct ways is to use ctx.transform() method documentation is here

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