简体   繁体   中英

Fabric.js – element is undefined when I move the mouse holding down the mouse button

I have a canvas made up by many circels that have opacity = 0. I want to change this to 1 when I:

  1. click the circle
  2. move over the circle (with the cursor) when the mousebutton is down.

Nr 1 is easy. That is solved with a canvas.on('mouse:down......)

But I can´t figure out how I should solve issue nr 2. Here are some snippets from my code:

var mouseDown = 0;
document.body.onmousedown = function() { 
    mouseDown = 1;
}
document.body.onmouseup = function() {
    mouseDown = 0;
}

canvas.on('mouse:move', function(options) {
    if (mouseDown  && options.target) {
        options.target.set('opacity', 1)
        canvas.renderAll()
}});

But the option.target is ALWAYS undefined when the mousebutton is pressed

Object {target: undefined, e: MouseEvent}

I was using typescript with FabricJS and came across this same issue. I found that you could use canvas.findTarget method to get FabricJS to do this for you. I'm sure you can convert that into the corresponding javascript.

 canvas.on('mouse:move', (e) => { var target = canvas.findTarget(<MouseEvent>(ee), true); } 

I'm not all that familiar with Fabric.js, so there might be a better solution, but here's my take on it:

canvas.on('mouse:move',function(options){
    var pt = { x: options.e.clientX, y: options.e.clientY };
    if( circle.containsPoint(pt)  ) {
        if( !circle.mouseOver ) {
            circle.mouseOver = true;
            console.log( 'over circle, yo' );
            circle.set('opacity', 0.5);
            canvas.renderAll();
        }
    } else if( circle.mouseOver ) {
        circle.mouseOver = false;
        circle.set('opacity', 1.0);
        canvas.renderAll();
    }
});

Basically we're doing all the heavy lifting to see if we're over the object of interest, and changing its properties when we first mouse over it, and then again when we mouse out of it. You can combine this with your mouseDown variable to only take these actions when the mouse is down.

You can see my solution in action here:

http://jsfiddle.net/qwpB3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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