简体   繁体   English

Fabric.js –按住鼠标按钮移动鼠标时元素未定义

[英]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: 我有一个由许多不透明度= 0的圆形组成的画布。当我执行以下操作时,我想将其更改为1:

  1. click the circle 点击圈子
  2. move over the circle (with the cursor) when the mousebutton is down. 按下鼠标按钮时(使用光标)在圆上移动。

Nr 1 is easy. Nr 1很简单。 That is solved with a canvas.on('mouse:down......) 这可以通过canvas.on('mouse:down ......)来解决。

But I can´t figure out how I should solve issue nr 2. Here are some snippets from my code: 但是我不知道该如何解决问题2。这是我的代码中的一些摘要:

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 但是,当按下鼠标按钮时,option.target始终是未定义的

Object {target: undefined, e: MouseEvent}

I was using typescript with FabricJS and came across this same issue. 我在FabricJS中使用打字稿,并遇到了同样的问题。 I found that you could use canvas.findTarget method to get FabricJS to do this for you. 我发现您可以使用canvas.findTarget方法获取FabricJS为您执行此操作。 I'm sure you can convert that into the corresponding javascript. 我确定您可以将其转换为相应的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: 我对Fabric.js并不十分熟悉,因此可能会有更好的解决方案,但这是我的看法:

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. 您可以将其与mouseDown变量结合使用,以便仅在鼠标按下时执行这些操作。

You can see my solution in action here: 您可以在这里看到我的解决方案:

http://jsfiddle.net/qwpB3/ http://jsfiddle.net/qwpB3/

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

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