Aaron Halbleib
Aaron Halbleib

Reputation: 3

per pixel image object detection in fabric js

I have been trying to get the per pixel drag and drop feature working using images with fabric.js like in example on their website: http://fabricjs.com/per-pixel-drag-drop/. I would like the object to be detected when a non transparent part is moused over but if I set perpixeltargetfind to true nothing is detected. I have tried for a while now and even copying the example verbatim while using my own images has not worked. Would really appreciate some help figuring out what I am doing wrong if anyone has experience using this. Thanks. Here is a link to a js fiddle I have been using: http://jsfiddle.net/ahalbleib/bdofdbqg/ and the code:

var canvas =this.__canvas = new fabric.Canvas('c1',{hoverCursor: 'pointer',
    selection: false});
var urls=['https://dl.dropboxusercontent.com/s/ix6mvv49wnx226a/Central-Richmon_clipped_rev_1.png?dl=0' , 
        'https://dl.dropboxusercontent.com/s/jjp2l0kgdw8iitb/Laurel-Heights.png?dl=0',
        'https://dl.dropboxusercontent.com/s/wdk02w40z1466g5/LoneMountain.png?dl=0',
        'https://dl.dropboxusercontent.com/s/t6tnptndu2k22xr/OuterRichmond.png?dl=0',
        'https://dl.dropboxusercontent.com/s/tv4rhwjc0nw35iz/Presidio-Heights.png?dl=0' ,
        'https://dl.dropboxusercontent.com/s/ttbf390w2vdx4id/Inner-richmond.png?dl=0'];
for (var i=0; i<urls.length; i++){
    fabric.Image.fromURL( urls[i], function(img){

        img.perPixelTargetFind = true;
         img.targetFindTolerance = 4;
          img.hasControls = img.hasBorders = false;
          canvas.add(img);

    }); 
}

canvas.findTarget = (function (originalFn) {
    return function () {
        var target = originalFn.apply(this, arguments);
        if (target) {
            if (this._hoveredTarget !== target) {
                canvas.fire('object:over', { target: target });
                if (this._hoveredTarget) {
                    canvas.fire('object:out', { target: this._hoveredTarget });
                }
                this._hoveredTarget = target;
            }
        }
        else if (this._hoveredTarget) {
            canvas.fire('object:out', { target: this._hoveredTarget });
            this._hoveredTarget = null;
        }
        return target;
    };
})(canvas.findTarget);

};

init();

Upvotes: 0

Views: 1160

Answers (1)

Nistor Cristian
Nistor Cristian

Reputation: 1266

That is because you don't take images from your own server and you'll get a Security error about tainted canvas. You need to set crossOrigin: 'Anonymous' to images. I made you a jsFiddle

Upvotes: 1

Related Questions