How to put an html element over a fabric.js element

我是研究僧i 提交于 2021-01-28 05:22:45

问题


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 then set it to the button?.

jsfiddle: https://jsfiddle.net/d9sp16yc/2/

I've tried things like this or this but I don't get the results that I want. The button gets slightly moved to right or left / bottom or top.

Another thing is that the setSize function is scaling the group when the window gets resized (just to get a responsive behaviour):

function setSize() {
  var width = $('.container').width();
  var height = width * 0.6;
  canvas.setWidth(width);
  canvas.setHeight(height);
  group.scaleToWidth(width);
  canvas.centerObjectH(group);
  // setPos($('#btn'), rect);
}

And the problem is that this affects the way the coords are being calculated.

Is this possible to put it in the top-left corner of the fabric object even when the window gets resized?

I really need a quick solution for this so I would appreciate any suggestion/help to achieve this.

Thanks in advance.


回答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.

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

  function positionBtn(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);
  });
})();


来源:https://stackoverflow.com/questions/43507133/how-to-put-an-html-element-over-a-fabric-js-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!