Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I put the origin of the canvas in the center

I am trying to write simple turtle graphics for my Transcrypt Python to JavaScript compiler. To be compatible with the CPython Turtle module, I need carthesian coordinates, i.e. the origin must be in the center of the canvas. Is there any way I can achieve that without using a separate coordinate system myself and transforming them for each object in my own code.

I've seen that for individual objects I can use centerX and centerY to center their reference point inside such object. But I couldn't find an example of putting the origin in the middle of the canvas.

The solution given in How to change the origin of the canvas to the center? works, but looks somewhat artificial, as I would to compensate the mouse position for this translation. Also it gives a strange "doubling" of some line segments, probably due to an offset. If a translate the coordinates in my own code, the doubling is absent. Both translations add integers.

Translation using canvas context

Translation using canvas context, some lines double. Code:

class Turtle:
    def __init__ (self):
        self._canvas = __new__ (fabric.Canvas ('canvas', {'backgroundColor': 'lightgray'}))
        self._canvas.onWindowResize = self.resize
        self._canvas.onWindowDraw = self.draw

        self._context = self._canvas.getContext ('2d')
        self._context.translate (self._canvas.getWidth () / 2, self._canvas.getHeight () / 2)

        self.reset ()

    def reset (self):
        self._canvas.clear ()   
        self.pensize (1)
        self.color ('black')
        self.down ()
        self._position = [0, 0]
        self._heading = Math.PI / 2

Translation in my application code

Translation in my application code, as it should look. Code:

class Turtle:
    def __init__ (self):
        self._canvas = __new__ (fabric.Canvas ('canvas', {'backgroundColor': 'lightgray'}))
        self._canvas.onWindowResize = self.resize
        self._canvas.onWindowDraw = self.draw

        self._context = self._canvas.getContext ('2d')

        self.reset ()

    def reset (self):
        self._canvas.clear ()   
        self.pensize (1)
        self.color ('black')
        self.down ()
        self._position = [self._canvas.getWidth () / 2, self._canvas.getHeight () / 2]
        self._heading = Math.PI / 2
like image 389
Jacques de Hooge Avatar asked Dec 05 '25 07:12

Jacques de Hooge


1 Answers

To avoid de "doubling" effect you can try this:

self._context.translate (round(self._canvas.getWidth () / 2), round(self._canvas.getHeight () / 2))
like image 180
Pierre-Jean Coudert Avatar answered Dec 10 '25 04:12

Pierre-Jean Coudert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!