Skip to content

Instantly share code, notes, and snippets.

@mpmckenna8
Last active August 10, 2016 20:53
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 mpmckenna8/737071b22692f9c1c553150ee0fccffd to your computer and use it in GitHub Desktop.
Save mpmckenna8/737071b22692f9c1c553150ee0fccffd to your computer and use it in GitHub Desktop.
canvas animate

Makes a graph of sin(4 theta) with just a hundred points. Still looks pretty good.

Built with blockbuilder.org

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
svg { width:100%; height: 100% }
</style>
</head>
<body>
<canvas width=600 height=350 id='canvas-1'></canvas>
<script>
// Feel free to change or delete any of the code you see!
// get the canvas element
var canvas = document.getElementById('canvas-1');
// get a context to draw in
var ctx = canvas.getContext('2d');
var height = 350;
var width = 500;
function tick() {
// clear what was drawn in the previous frame
canvas.width = canvas.width;
// begin a new path: arc is a line instruction like lineTo
ctx.beginPath();
// define the circle: position according to time, 50px radius
ctx.arc((Date.now() / 10) % 500 + 50, 50 + Math.sin(Date.now() / 100) * 10, 50, 0, 2 * Math.PI);
ctx.fillStyle = "green";
ctx.fill()
ctx.arc(((Math.sin(new Date() / 1000) + 1) % 2) * 500 + 50, 50, 50, 0, 2 * Math.PI);
ctx.fillStyle = "purple";
// draw the circle
ctx.fill();
// request a chance to draw the circle again as soon as possible
requestAnimationFrame(tick);
}
var ball = {
x: 100,
y: 100,
radius: 35,
color: 'blue',
draw: function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, true);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
}
};
ball.draw();
//tick();
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment