Search code examples
javascripthtmlcanvastransparencykineticjs

Make transparent eraser in kineticjs


Hi how to make transparent eraser using kineticjs or just using canvas.

I need to erase part of polygon which is over some image, make just part of polygon transparent and image should stay the same.


Solution

  • You need access to context's globalCompositeOperation="destination-out" which acts as an "eraser". The KineticJS context does not give you globalCompositeOperation so you'll have to dig to get the "real" html canvas context:

    • Put your image on the bottom layer
    • Put your polygon on the top layer
    • Put a custom shape on the top layer
    • Use the custom shape to get to an html canvas context [context=layer.getContext()._context]
    • Use context.globalCompositeOperation="destination-out" to "erase" the polygon and let the image underneath show through.

    Here's an example of the shape object that "erases" to the image:

    http://jsfiddle.net/m1erickson/yv9qn/

    var myShape = new Kinetic.Shape({
      x: 0,
      y: 0,
      fill:"blue",
      drawFunc: function(context) {
        var ctx=layer.getContext()._context;
        ctx.save();
        ctx.globalCompositeOperation="destination-out";
        for(var i=0;i<this.cutouts.length;i++){
            var cut=this.cutouts[i];
            ctx.fillRect(cut.x,cut.y,cut.width,cut.height);
        }
        ctx.restore();  
      }
    });
    myShape.cutouts=[];
    layer.add(myShape);
    
    myShape.cutouts.push({x:75,y:75,width:30,height:30});
    myShape.cutouts.push({x:225,y:75,width:30,height:30});
    myShape.cutouts.push({x:150,y:125,width:30,height:30});