Skip to content

Instantly share code, notes, and snippets.

@louisbros
Last active August 29, 2015 14:23
Show Gist options
  • Save louisbros/354261b0b98430148d4f to your computer and use it in GitHub Desktop.
Save louisbros/354261b0b98430148d4f to your computer and use it in GitHub Desktop.
Animated Sine Wave
/*
<style>
html, body {
margin:0;
padding:0;
}
#canvas-wrapper {
margin: 20px auto 10px auto;
width:600px;
height:600px;
border-left: 1px solid #aaa;
border-bottom: 1px solid #aaa;
}
#ball-wrapper {
position:relative;
margin: 0 auto;
width:600px;
}
#ball {
position:absolute;
left:100%;
width:20px;
height:20px;
background-color:#4072B4;
border-radius:50%;
}
</style>
<div id="canvas-wrapper">
<canvas id="canvas" />
</div>
<div id="ball-wrapper">
<div id="ball" />
</div>
*/
var canvasWrapper = document.getElementById('canvas-wrapper');
var canvas = document.getElementById('canvas');
var ballWrapper = document.getElementById('ball-wrapper');
var ball = document.getElementById('ball');
var ctx = canvas.getContext('2d');
var width = canvasWrapper.clientWidth;
var height = canvasWrapper.clientHeight;
canvas.width = width;
canvas.height = height;
function toRadian(degree) {
return degree * Math.PI / 180;
}
function toDegree(radian) {
return radian * 180 / Math.PI;
}
function drawGrid(ctx) {
ctx.fillStyle = '#ddd';
for (var i = 0;i < width;i++) {
if (i % 12 === 0 && i !== 0) {
ctx.fillRect(i, 0, 1, height);
}
}
for (var j = 0;j < height;j++) {
if (j % 12 === 0 && j !== 0) {
ctx.fillRect(0, j, width, 1);
}
}
}
function drawPoint(ctx, x, y) {
ctx.fillStyle = '#4072B4';
ctx.fillRect(x, height - y, 2, 2);
}
function moveBall(ball, d) {
ball.style.bottom = d + 'px';
}
function draw(start, duration, distance) {
var t = new Date().getTime() - start;
if (t >= duration) {
return;
}
var d = distance * Math.sin(t / duration * toRadian(90));
drawPoint(ctx, t/(duration / 600), d);
moveBall(ball, d);
setTimeout(function() {
draw(start, duration, distance);
}, 1000 / 60);
}
drawGrid(ctx);
draw(new Date().getTime(), 2400, 600);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment