【问题标题】:Draw rectangle on mousedown event在 mousedown 事件上绘制矩形
【发布时间】:2018-11-20 17:28:56
【问题描述】:

我在 Fabric.js 中构建了一个基本的可缩放和可平移画布。我需要在单击坐标位置的每个 mousedown 事件上绘制一个矩形。当画布从其初始状态转换时会出现问题 - 绘图不准确,因为必须使用新矩阵转换坐标。

如何使用新矩阵转换鼠标事件的坐标?

这是我正在使用的代码。谢谢

canvas.on('mouse:down', function (opt) {
  const evt = opt.e;
  const p = new fabric.Rect({
    left: opt.e.offsetX,
    top: opt.e.offsetY,
    fill: 'red',
    width: 30,
    height: 30,
  });
  canvas.add(p);
});

更新 1: 我找到了一种转换点的方法 (fabric.util.transformPoint()),但是 根据画布上下文,转换后的点不正确。

  const evt = opt.e;
  const point = new fabric.Point(opt.e.offsetX, opt.e.offsetY);
  const transformedPoint = fabric.util.transformPoint(point, this.viewportTransform);
  const p = new fabric.Rect({
    left: transformedPoint.x,
    top: transformedPoint.y,
    fill: 'red',
    width: 30,
    height: 30,
  });
  this.add(p);

【问题讨论】:

  • “它不适合我”是什么意思?
  • 对不起,我的意思是根据画布上下文转换的点不正确(使用 fabric.util.transformPoint())

标签: javascript html5-canvas fabricjs


【解决方案1】:

我终于通过使用倒置矩阵的 fabric.util.transformPoint() 解决了这个问题。这是将画布中的点转换为画布上下文中的点的代码。

  const point = new fabric.Point(offsetX, offsetY);
  const invertedMatrix = fabric.util.invertTransform(canvas.viewportTransform)
  const transformedPoint = fabric.util.transformPoint(point, invertedMatrix);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 2011-12-05
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多