Skip to content

Instantly share code, notes, and snippets.

@towc
Created July 14, 2015 09:52
Show Gist options
  • Select an option

  • Save towc/0e351f7feeb36fdce04c to your computer and use it in GitHub Desktop.

Select an option

Save towc/0e351f7feeb36fdce04c to your computer and use it in GitHub Desktop.
the meaning of points, lines and animation
<canvas id=c></canvas>
var w=window.innerWidth,
h=window.innerHeight;
c.width=w; c.height=h;
var ctx=c.getContext('2d');
var points=[];
var vels=[];
for(var i=0; i<30; ++i){
points.push({x:(Math.random()*w)|0, y:(Math.random()*h)|0});
vels.push({x:(Math.random()-0.5)*4, y:(Math.random()-0.5)*4})
}
function draw(x, y){
for(var i=0; i<points.length; ++i){
var endX=points[i].x+vels[i].x;
var endY=points[i].y+vels[i].y
if(endX<0||endX>w) vels[i].x*=-1;
if(endY<0||endY>h) vels[i].y*=-1;
points[i].x+=vels[i].x;
points[i].y+=vels[i].y;
vels[i].x+=(mX-points[i].x)/1000;
vels[i].y+=(mY-points[i].y)/1000;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(points[i].x, points[i].y);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.arc(points[i].x, points[i].y, 2, 0, Math.PI*2);
ctx.fill();
ctx.closePath();
}
}
ctx.strokeStyle='rgba(100, 100, 100, 0.05)';
var mX=w/2,
mY=h/2;
function anim(){
window.requestAnimationFrame(anim);
ctx.fillStyle='rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, w, h);
ctx.fillStyle='rgb(100, 100, 10)';
draw(mX, mY);
}
anim();
document.addEventListener('mousemove', function(e){
mX=e.clientX;
mY=e.clientY;
})
canvas{
position:absolute;
top:0px; left:0px;
}
canvas:hover{
cursor:crosshair;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment