fabricjs - 如何将 Canvas 的原点放在中心

标签 fabricjs transcrypt

我正在尝试为我的 Transcrypt 编写简单的乌龟图形Python 到 JavaScript 编译器。为了与 CPython Turtle 模块兼容,我需要笛卡尔坐标,即原点必须位于 Canvas 的中心。有什么方法可以实现这一点,而无需我自己使用单独的坐标系并在我自己的代码中为每个对象转换它们。

我已经看到,对于单个对象,我可以使用 centerX 和 centerY 将它们的引用点置于此类对象的中心。但是我找不到将原点放在 Canvas 中间的示例。

How to change the origin of the canvas to the center?中给出的解决方案有效,但看起来有些人为,因为我会为此翻译补偿鼠标位置。它还给出了一些线段的奇怪“加倍”,可能是由于偏移。如果在我自己的代码中翻译坐标,则不存在加倍。两种翻译都添加整数。

Translation using canvas context

翻译使用 Canvas 上下文,有些行加倍。代码:

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

我的应用程序代码中的翻译,看起来应该是这样。 代码:

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

最佳答案

为了避免去“加倍”的效果,你可以试试这个:

self._context.translate (round(self._canvas.getWidth () / 2), round(self._canvas.getHeight () / 2))

关于fabricjs - 如何将 Canvas 的原点放在中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37224200/

相关文章:

javascript - 在 javascript 中创建 3d 屋顶

fabricjs - 在fabricjs中在图像上添加文本

ios - Fabric js 文本字符在 iPhone 和 iPad 上出现乱码

python - 了解 Transcrypt 自动测试如何记录代码

javascript - Transcrypt:如何使用 Python/Flask 发送 ajax POST 请求以启动服务器端作业

javascript - fabric.js fabric.Image.fromURL 在使用外部 url 时抛出错误

javascript - 如何将图像添加到织物 Canvas ?

python - 数据类行为的变化

python - 如何测试 transcrypt 中的未定义