JSFiddle - React, Tailwind, and code Playground
by m1erickson
HTML
<p>Image clipped by moving circle</p>
<canvas id="canvas" width=300 height=200></canvas>
<br/>
<p>Unclipped image</p>
<canvas id="image" width=300 height=200></canvas>
CSS
body {
background-color: ivory;
}
canvas {
border:1px solid red;
}
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
window.requestAnimFrame = (function (callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var radius = 50;
var x = 100;
var dx = 10;
var y = 100;
var dy = 10;
var delay = 10;
var img = new Image();
img.onload = function () {
var canvas1 = document.getElementById("image");
var ctxImg = canvas1.getContext("2d");
ctxImg.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
animate();
}
img.src = "http://lh3.ggpht.com/_Z-i7eF_ACGI/TRxpFywLCxI/AAAAAAAAAD8/ACsxiuO_C1g/house%20vector.png";
function animate() {
if (--delay < 0) {
// update
x += dx;
if (x - radius < 0 || x + radius >= canvas.width) {
dx = -dx;
}
y += dy;
if (y - radius < 0 || y + radius >= canvas.height) {
dy = -dy;
}
delay = 10;
// draw stuff
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
ctx.clip();
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
ctx.restore();
}
// request new frame
requestAnimFrame(function () {
animate();
});
}