为了账号安全,请及时绑定邮箱和手机立即绑定

如何以编程方式正确移动对象?

如何以编程方式正确移动对象?

偶然的你 2021-11-18 15:46:14
我需要在鼠标光标之后移动对象。如果使用代码,我有很大的性能问题。canvas.on('mouse:move', (event) => {    const pointer = canvas.getPointer(event);    cursor.set({        top: pointer.y,        left: pointer.x,    });    canvas.renderAll();})据我所知,fabric 创建了 2 层,是否可以在顶层放置一个物体以进行移动?这是一个例子 https://jsfiddle.net/Warmor/7bL02sjv/38/
查看完整描述

1 回答

?
郎朗坤

TA贡献1921条经验 获得超9个赞

创建一个所有行的组,并删除perPixelTargetFind最重要的调用canvas#requestRenderAll,而不是canvas#renderAll


const canvas = new fabric.Canvas("canvas", {

  width: 500,

  height: 500,

  selection: false,

  centeredScaling: true,

});


const createLine = (index) => {

  return new fabric.Line([index * 5, 0, 500 - index * 5, 500], {

    stroke: "#000",

    strokeWidth: 1,

    fill: "#000"

  });

};

const lines = [];

for (i = 0; i < 100; i++) {

  lines.push(createLine(i));

}

const group = new fabric.Group(lines, {

  selectable: false

});

canvas.add(group);


const cursor = new fabric.Rect({

  stroke: "#000",

  strokeWidth: 1,

  fill: "red",

  width: 50,

  height: 50,

  top: 0,

  left: 0,

  selectable: false

});

canvas.add(cursor);


canvas.on('mouse:move', (event) => {

  const pointer = canvas.getPointer(event);

  cursor.set({

    top: pointer.y,

    left: pointer.x,

  });

  canvas.requestRenderAll();

})

.canvas {

  width: 1000px;

  height: 1000px;

  border: 1px solid Black;

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.js"></script>

<canvas id="canvas" class="canvas" ></canvas>


查看完整回答
反对 回复 2021-11-18
  • 1 回答
  • 0 关注
  • 152 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信