简体   繁体   English

fabric.js:将事件绑定到背景图像

[英]fabric.js: bind event to background image

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.我正在尝试绑定鼠标事件来处理拖动,因此当图像大于画布时,我可以移动图像,例如 background-cover css 属性。

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

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM