Search code examples
javascriptkineticjscroplayer

KineticJs - Merging an image onto another


I'd like to know if there is some way in Kinetic to have an image merged with another image on a lower layer, creating a kind of crop effect based on the shape of the "cropping" image.

The image must have a transparent background as a result, which is the main source of difficulty for me. I would otherwise just have used a mask with dragging turned off... I've made a diagram to explain what I want a bit better. Any suggestions welcome.

diagram

I've also made a quick jsfiddle, where I would like the contents of the image to be displayed inside the box. I feel like one layer is the way to go on this one.


Solution

  • You can use an offscreen Canvas element plus compositing to create your clipped image for use by your Kinetic.Image. Note that the offscreen canvas can be used as an image source for your Kinetic.Image.

    Example code and a Demo: http://jsfiddle.net/m1erickson/ks1xxqfL/

    var canvas=document.createElement('canvas');
    var ctx=canvas.getContext('2d');
    canvas.width=background.width;
    canvas.height=background.height;
    ctx.drawImage(mask,0,0,mask.width*2.25,mask.height*2.25);
    ctx.globalCompositeOperation='source-in';
    ctx.drawImage(background,0,0);
    
    var support=new Kinetic.Image({
        draggable:true,
        image:canvas,
    });
    layer.add(support);
    layer.draw();
    

    Illustrations

    • Left: the background image,
    • Center: the image to be used as a clipping mask
    • Right: the background clipped by the mask (mask was scaled by 2.25X)

    enter image description hereenter image description hereenter image description here