简体   繁体   中英

fabric.js | Check if mouse is down error

I get the following error:

Uncaught TypeError: Cannot read property 'setFill' of null

I am using fabric.js and the error occurs in the "options.target.setFill()..." line:

var mDown = false;
canvas.on('mouse:down', function(options) {
    mDown = true;
});
canvas.on('mouse:up', function(options) {
    mDown = false;
});
canvas.on('mouse:move', function(options) {
    if (mDown == true) {
        options.target.setFill('red');
        canvas.renderAll();
    }
});

Without the if condition, the "mouse:move" event works.

You must not be clicking on an object. Target is only set if you click an object. below I add a check to see if target is set. without that check I get the same error you explained.

You could also update your code to not listen to the canvas for click events and instead attach the event to the object themselves.

 var canvas = new fabric.Canvas("c"); var mDown = false; canvas.on('mouse:down', function(options) { mDown = true; }); canvas.on('mouse:up', function(options) { mDown = false; }); canvas.on('mouse:move', function(options) { if (mDown == true && options.target) { options.target.setFill('red'); canvas.renderAll(); } }); 
 canvas { border: 1px solid black; } 
 <canvas id="c" width="400" height="300"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.3/fabric.min.js"></script> 

I think what you need is object:moving not mouse:move event since mouse:move is triggered when you move your mouse point to the canvas, since no object is selected in you canvas, you get null.

take a look for the code below. I created a triangle and every time I moved it, it change its color. Hope you have an idea from this.

 var canvas = new fabric.Canvas('c'); var mDown = false; var triangle = new fabric.Triangle({ width: 20, height: 30, fill: 'blue', left: 50, top: 50 }); canvas.add(triangle); canvas.on('mouse:up', function(options) { mDown = false; triangle.set('fill', 'blue'); }); canvas.on('mouse:down', function(options) { mDown = true; //triangle.set('fill', 'blue'); }); canvas.on('object:moving', function(options) { if (mDown == true) triangle.set('fill', 'red'); //triangle.set('fill', 'red'); //canvas.add(triangle); }); 
 canvas { border: 1px solid black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.3/fabric.min.js"></script> <canvas id="c" width="400" height="300"></canvas> 

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