gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:15:37 25 4
gpt4 key购买 nike

我正在尝试为我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com