JSFiddle - React, Tailwind, and code Playground
HTML
<h4>Wipe transition between images using canvas</h4>
<button id=again>Again</button><br><br>
<canvas id="canvas" width=300 height=300></canvas>
CSS
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
JavaScript
invar canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw,ch;
var x=0;
var eWidth=100;
var img1=new Image();
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/sailboat.png";
function start(){
cw=canvas.width=img.width;
ch=canvas.height=img.height;
img1.onload=function(){
requestAnimationFrame(animate);
};
img1.src="https://dl.dropboxusercontent.com/u/139992952/multple/sailboat1.png";
}
function draw() {
// create gradient
gradient = ctx.createLinearGradient(x-eWidth,0, x,0);
gradient.addColorStop(0, "rgba(0,0,0, 0)");
gradient.addColorStop(1, "rgba(0,0,0, 1)");
// save the unaltered canvas context
ctx.save();
// clear the canvas
ctx.clearRect(0,0,cw,ch);
// gradient zone
ctx.fillStyle = gradient;
ctx.fillRect(x-eWidth,0,eWidth,ch);
// fully original right of x
ctx.fillStyle='black';
ctx.fillRect(x,0,cw,ch);
// original image with gradient "dissolve" on left
// set compositing to source-in
ctx.globalCompositeOperation='source-in';
ctx.drawImage(img,0,0);
// revealed image
ctx.globalCompositeOperation='destination-over';
ctx.drawImage(img1,0,0);
// restore the context to its unaltered state
ctx.restore();
}
function animate() {
if (x<cw+eWidth){ requestAnimationFrame(animate); }
x-=5;
draw();
}
$('#again').click(function(){
x=0;
requestAnimationFrame(animate);
});