Skip to content Skip to sidebar Skip to footer

How To Put An Html Element Over A Fabric.js Element

I want to put a button over a fabric.js element which is inside of a fabric.Group. How do I get the top-left corner coords relative to the canvas container of a fabric element and

Solution 1:

Take a look at this (Interaction with objects outside canvas). I hope it helps...

In a nutshell you can use the absolute coordinates of an object inside the canvas to position an HTML element out of the canvas.

Here is the code and a screenshot from the website. It simply positions HTML button over a fabric image element and assigns move event on the image, so when you move the image, the button follows it.

enter image description here

(function() {
  var canvas = this.__canvas = new fabric.Canvas('c');
  fabric.Object.prototype.transparentCorners = false;
  fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center';

  fabric.Canvas.prototype.getAbsoluteCoords = function(object) {
    return {
      left: object.left + this._offset.left,
      top: object.top + this._offset.top
    };
  }

  var btn = document.getElementById('inline-btn'),
      btnWidth = 85,
      btnHeight = 18;

  functionpositionBtn(obj) {
    var absCoords = canvas.getAbsoluteCoords(obj);

    btn.style.left = (absCoords.left - btnWidth / 2) + 'px';
    btn.style.top = (absCoords.top - btnHeight / 2) + 'px';
  }

  fabric.Image.fromURL('../lib/pug.jpg', function(img) {

    canvas.add(img.set({ left: 250, top: 250, angle: 30 }).scale(0.25));

    img.on('moving', function() { positionBtn(img) });
    positionBtn(img);
  });
})();

Post a Comment for "How To Put An Html Element Over A Fabric.js Element"