JSFiddle - React, Tailwind, and code Playground

by m1erickson

HTML

<p>Images clipped inside triangular canvas paths</p>
<canvas id="canvas" width=350 height=200></canvas>
<p>Original Images</p>

CSS

body{ background-color: ivory; }
canvas{border:1px solid red;}

JavaScript

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

// image loader
// put the paths to your images in imageURLs[]
var imageURLs=[];  
// push all your image urls!
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/norwayFlag.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/swedishFlag.jpg");

// the loaded images will be placed in images[]
var imgs=[];

var imagesOK=0;
loadAllImages(start);

function loadAllImages(callback){
    for (var i=0; i<imageURLs.length; i++) {
        var img = new Image();
        imgs.push(img);
        img.onload = function(){ 
            imagesOK++; 
            if (imagesOK>=imageURLs.length ) {
                callback();
            }
        };
        img.onerror=function(){alert("image load failed");} 
        img.crossOrigin="anonymous";
        img.src = imageURLs[i];
    }      
}

function start(){
    
    // the imgs[] array now holds fully loaded images
    // the imgs[] are in the same order as imageURLs[]
    
    // clip image#1
    clippingPath([10,70,50,10,90,70],imgs[0],10,10);
    
    // clip image#2
    clippingPath([10,170,50,110,90,170],imgs[1],10,110);

    // clip image#1 again
    clippingPath([110,70,150,10,190,70],imgs[0],110,10);
    
    // append the original images for demo purposes
    document.body.appendChild(imgs[0]);
    document.body.appendChild(imgs[1]);
    
}

function clippingPath(pathPoints,img,x,y){
    
    // save the unclipped context
    ctx.save();
    
    // define the path that will be clipped to
    ctx.beginPath();
    ctx.moveTo(pathPoints[0],pathPoints[1]);
    ctx.lineTo(pathPoints[2],pathPoints[3]);
    ctx.lineTo(pathPoints[4],pathPoints[5]);
    ctx.closePath();    
    
    // stroke the path
    // half of the stroke is outside the path
    // the outside stroke will survive the clipping that follows
    ctx.lineWidth=2;
    ctx.stroke();
    
    // make the current path a clipping path
   ...