fabric.js: bind event to background image

痞子三分冷 提交于 2021-01-28 23:38:08

问题


I'm trying to bind an event to a background image:

var imgInstance = fabric.Image.fromURL(path, function(oImg) {

    oImg.on("selected", function() {
        alert();
    });

    canvas.setBackgroundImage(oImg, canvas.renderAll.bind(canvas), {
        top: 0,
        left: 0
    });

    oImg.on("selected", function() {
        alert();
    });
});

I can get it work. I'm trying to bind mouse events to handle drag, so i can move the image when it's bigger than the canvas, like background-cover css property.

Thoughts?

Thanks guys!

SOLUTION:

var DragStart = false;

canvas.on('mouse:down', function(options) {
    if (!options.target) {
        DragStart = true;
    }else {
        DragStart = false;
    }
});

canvas.on('mouse:move', function(options) {
    if (DragStart) {

        var bounds = getBounds(options.e); // validate boundaries between image and canvas

        canvas.backgroundImage.top = bounds.y;
        canvas.backgroundImage.left = bounds.x;
        canvas.renderAll();
    }
});

回答1:


It doesn't seem like you can add events to the background image... but the canvas does emit events and if you click the canvas and no target is set then they must be clicking the background. Background image are not forced to take up the whole background but I'm not sure reasons to not make it take up the whole background.

You do get the mouse event passed in though so if the background image does not take up the whole background you could do that math and figure out where they clicked.

window.canvas = new fabric.Canvas('c', { selection: false, preserveObjectStacking:true });

fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(o) {
	canvas.setBackgroundImage(o, canvas.renderAll.bind(canvas), {
    top: 0,
    left: 0
  });
});

canvas.on('mouse:down', function(options) {
  if (!options.target) {
  	console.log('target is null')
  
  }
});


canvas.add(new fabric.Rect({ 
  left: 100, 
  top: 100, 
  width: 50, 
  height: 50, 
  fill: '#faa', 
  originX: 'left', 
  originY: 'top',
  centeredRotation: true
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
<canvas id="c" width="600" height="600"></canvas>


来源:https://stackoverflow.com/questions/39903219/fabric-js-bind-event-to-background-image

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