Skip to content

Instantly share code, notes, and snippets.

@edwardlorilla
Created June 2, 2021 16:30
Show Gist options
  • Save edwardlorilla/aa581e4caa5d5b90b96a61cc44ccf1b2 to your computer and use it in GitHub Desktop.
Save edwardlorilla/aa581e4caa5d5b90b96a61cc44ccf1b2 to your computer and use it in GitHub Desktop.
【JAVASCRIPT】Mask or clip the image on canvas and move it
<canvas id="canvas" width="480" height="360"></canvas>
var w = 480;
var h = 360;
var c = 0;
window.onload = function() {
draw();
}
function draw() {
var canvas = document.getElementById('canvas');
if(!canvas || !canvas.getContext) return false;
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'https://picsum.photos/480/360';
img.onload = function() {
setInterval(function() {
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.arc(c, 180, 100, 0, Math.PI * 2, false);
ctx.arc(w - c, 180, 100, 0, Math.PI * 2, false);
ctx.clip();
ctx.drawImage(img, 0, 0);
c += 1;
if(c > w) {
c = 0;
}
}, 20);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment