Skip to content

Instantly share code, notes, and snippets.

@shshaw
Created March 15, 2018 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shshaw/6c443248da93f65b8474b95761da07c8 to your computer and use it in GitHub Desktop.
Save shshaw/6c443248da93f65b8474b95761da07c8 to your computer and use it in GitHub Desktop.
Canvas Clip
<script>console.clear();</script>
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
var width = canvas.width = window.innerWidth,
height = canvas.height = window.innerHeight;
window.addEventListener('resize',function(){
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
});
document.body.appendChild(canvas);
function drawText(){
ctx.font = 'bold 48px sans-serif';
ctx.textAlign = 'center';
ctx.fillText('Canvas clip()', width/2, height/2 + 15);
}
function circleClip(x, y, radius, color, textColor){
ctx.save();
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.clip();
ctx.fillStyle= color;
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = textColor;
drawText();
ctx.restore();
}
var circles = [
// Blue
{
x: width * 0.75,
y: (height * 0.5 + 10),
r: 50,
c: '#005792',
t: '#00BBF0'
},
// Green
{
x: width * 0.25,
y: (height * 0.5 - 50),
r: 50,
c: '#6BA083',
t: '#BCFFA8'
},
// Red
{
x: width * 0.5,
y: height * 0.5,
r: 50,
c: '#FF6464',
t: '#FFAA64'
},
];
function render(){
requestAnimationFrame(render);
ctx.clearRect(0, 0, width, height);
drawText();
for (var i = 0, len = circles.length; i < len; i++){
var c = circles[i];
circleClip(c.x, c.y, c.r, c.c, c.t);
}
}
var tl = new TimelineMax({ repeat: -1 });
tl.timeScale(1.25);
tl.staggerFromTo(circles, 2, {
cycle: {
x: function(i){ return width * 0.5 - ( i * 40 ) + 40; },
y: function(i){ return height * 0.5; }
}
},{
cycle: {
x: function(i){
return (width * 0.5) + 140 - (i * 40);
},
y: function(i){
return (height * 0.5) - (i % 2 * 40) + 20;
}
},
ease: Expo.easeInOut
}, -0.5);
tl.staggerTo(circles, 2, {
cycle: {
x: function(i){
return (width * 0.5) - 140 + (i * 40);
},
y: function(i){
return (height * 0.5) + (i % 2 * 40) - 20;
}
},
ease: Expo.easeInOut
}, -0.5, '-=0.75');
tl.staggerTo(circles, 2, {
cycle: {
x: function(i){ return width * 0.5 - ( i * 40 ) + 40; },
y: function(i){ return height * 0.5; }
},
ease: Expo.easeInOut
}, -0.5, '-=0.75');
render();
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/TweenMax.min.js"></script>
<script src="https://codepen.io/shshaw/pen/epmrgO"></script>
canvas { display: block; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment