Skip to content

Instantly share code, notes, and snippets.

@sortofsleepy
Last active August 29, 2015 14:17
Show Gist options
  • Save sortofsleepy/df656f6fe7f83b5155dc to your computer and use it in GitHub Desktop.
Save sortofsleepy/df656f6fe7f83b5155dc to your computer and use it in GitHub Desktop.
A attempt at making a sine wave draw continuously. Nearly there! but needs a bit of work.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="rStats.css"/>
<style>
canvas{
position: absolute;
padding:0;
margin:0;
top:0;
left:0;
}
</style>
</head>
<body>
<canvas width="800" height="400" id="milkshake"></canvas>
<script>
/**
* Super hacky and definitely needs more work(probably better way of doing it too) but so far
* the most consistent implementation.
* @type {HTMLElement}
*/
var canvas = document.querySelector("#milkshake");
var ctx = canvas.getContext('2d');
//value used to shift drawing towards the left + keep a continuous drawing going
var value = 0;
//style of the wave + other lines
ctx.strokeStyle = "#ff0000"
//padding value to help ensure that the canvas is clear
var canvasClear = 0;
function animate(){
window.requestAnimationFrame(animate);
//need to clear canvas each frame. Need to add some padding as well otherwise it'll overdraw
ctx.clearRect(0,0,canvas.width + canvasClear,canvas.height);
//keep the drawing moving left
value += 4;
ctx.translate(-value * 0.0005,0);
//increment padding
canvasClear += value * 0.0005;
ctx.save();
ctx.beginPath();
for(var x = 0; x < value * 2; x+=1) {
// Sine wave equation. 60 is the amplitude. 9.05 should be the period.
var y = 60 * Math.sin(x / 9.05);
y += 80; // just so it doesn't hit the bounding box
ctx.lineTo(x, y);
ctx.lineWidth = 1;
}
ctx.stroke();
ctx.restore();
ctx.save();
}
//draw circle
drawCircle(100,100,130);
//mask things off so future drawing occurs within the circle
ctx.clip();
//draw the lines
animate();
function drawCircle(x,y,radius,stroke){
ctx.save();
stroke = stroke != undefined ? stroke : 5;
ctx.lineWidth = stroke;
//NOTE : x and y mark the center of the circle, not the top left of the bounding box
ctx.beginPath();
ctx.arc(x,y,radius,0,2 * Math.PI);
ctx.stroke();
ctx.closePath();
ctx.restore();
}
//from earlier experimenting, might prove useful
function wave(x,y,width,amplitude){
x = x !== undefined ? x : 0;
y = y !== undefined ? y : 75;
width = width !== undefined ? width : 400;
amplitude = this.amplitude !== undefined ? amplitude : 60;
var start = x;
var end = x + width;
var yPos = y;
var amplitude = amplitude;
ctx.save();
ctx.beginPath();
for(var x = start; x < end; x++) {
// Sine wave equation
var y = amplitude * Math.sin(x / 9.05);
y += yPos; // just so it doesn't hit the bounding box
ctx.lineTo(x, y);
}
ctx.moveTo(end - 2,yPos);
ctx.stroke();
ctx.restore();
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment