How to correctly move an object programmatically?

I need to move the object after the mouse cursor. If using code, I have big performance issues.

canvas.on('mouse:move', (event) => {
    const pointer = canvas.getPointer(event);
    cursor.set({
        top: pointer.y,
        left: pointer.x,
    });
    canvas.renderAll();
})

As far as I know, fabric creates 2 layers, is it possible to place an object on the top layer for movement?

Here is an example https://jsfiddle.net/Warmor/7bL02sjv/38/

Upvotes: 1

Views: 103

Answers (1)

Durga
Durga

Reputation: 15614

Create a Group of all lines, and remove perPixelTargetFind, and most important call canvas#requestRenderAll, not canvas#renderAll.

DEMO

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>

Upvotes: 1

Related Questions