Skip to content

Instantly share code, notes, and snippets.

@Rybar
Created January 22, 2015 05:55
Show Gist options
  • Save Rybar/f9e10e51ca3e5cead6ae to your computer and use it in GitHub Desktop.
Save Rybar/f9e10e51ca3e5cead6ae to your computer and use it in GitHub Desktop.
canvas play: rainbow squiggle

canvas play: rainbow squiggle

Lots of "magic numbers" going on here for the motion and color, my goal was simply to learn how to animate within a canvas element. My one struggle on this one was figuring out how to make a line made up of individual circles seem continuously drawn despite the speed increase. Eureka moment came when I realized I could just draw more than 1 per frame.

A Pen by Ryan Malm on CodePen.

License.

<canvas id="paper" width="640" height="480">
Y ur browser no have canvas??
</canvas>
var canvas = document.getElementById("paper");
var ctx = canvas.getContext("2d");
var dx = 0; //delta for movement
var dy = 0; //delta for movement
var mx = 0; //actual movement
var my = 0; //actual movement
draw = function(){
requestAnimationFrame(draw);
ctx.fillStyle = "rgba(0,0,0,0.04)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for(i=0; i < 15; i++){
dx += 11;
dy += 7;
mx = ( Math.cos(dx/243) + Math.cos(dy/253) ) * 100;
my = ( Math.sin(dx/347) + Math.cos(dy/363) ) * 100;
var r = Math.abs(Math.round(Math.cos(dx/2000)*255));
var g = Math.abs(Math.round(Math.sin(dx/1000)*255));
var b = Math.abs(Math.round(Math.cos(dx/1500)*255));
ctx.fillStyle = "rgba(" +r+ "," +g+ "," +b+ ",1)";
//console.log(ctx.fillStyle);
ctx.beginPath();
ctx.arc( canvas.width/2+mx, canvas.height/2+my, 5, 0, Math.PI*2, false );
ctx.fill();
}
//if(dx > canvas.width){
//dx = -50;
//}
}
draw();
body {
background-color:#000000;
}
#paper {
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment