netishix
netishix

Reputation: 193

Draw rectangle on mousedown event

I have a basic zoomable and pannable canvas build in Fabric.js. I need to draw a rectangle on every mousedown event at the clicked coordinate position. The problem happens when the canvas is transformed from it's initial state - the drawing is not accurate because the coordinates must be transformed with the new matrix.

How can I transform the coordinates from the mouse event using the new matrix?

Here is the code I am using. Thanks

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);
});

Update 1: I found a method to transform points (fabric.util.transformPoint()), but the transformed points were not correct according to the canvas context.

  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);

Upvotes: 0

Views: 401

Answers (1)

netishix
netishix

Reputation: 193

I finally solved it using fabric.util.transformPoint() using an inverted matrix. Here is the code for transforming a point in the canvas to a point in the canvas context.

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

Upvotes: 1

Related Questions