Have what I think seems like a kind of strange problem.
I have a function that is made to draw an element in HTML5.
If i write it multiple times it is drawn those times, but if i place it in a loop it only draws the first time. Iv tried to monitor this by console.log for example but as soon as i try to draw this the loop is interrupted. It like there is some type of "break" function in it.
Anyone who has an idea about this?
<body>
<section id="wrapper">
<h1></h1>
<canvas id="canvas" width="800" height="600" style=" border-color: #000; border-style: solid; border-width: 1px;">
<p>Your browser doesn't support canvas.</p>
</canvas>
<script>
var context;
var canvas;
var WIDTH;
var HEIGHT;
$(document).ready(function() {
main_init();
});
function main_init() {
console.log("init");
WIDTH = $("#canvas").width();
HEIGHT = $("#canvas").height();
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
var width = 10;
var height = 10;
var posX = 30;
var posY = 60;
//NOT WORKING
for(y = 1; y < height; y+=1)
{
for(x = 1; x < width; x+=1)
{
console.log("y:"+ y + " x:" + x);
//console.log(isEven(x));
if(isEven(x))
{
HexagonObj(posX * x, posY * y, 0.95);
}
else
{
HexagonObj(posX * x, (posY + 20) * y, 0.95);
}
}
}
//WORKING
HexagonObj(-30, 60, 0.95);
HexagonObj(10, 80, 0.95);
HexagonObj(50, 60, 0.95);
HexagonObj(-30, 100, 0.95);
}
HexagonObj = function(xCorrd, yCorrd, size){
//console.log("hexagon");
var x0=xCorrd; var y0=yCorrd; //cordinates
var xx=20 * size; var yy=20 * size; //size of the legs of the shape
x=x0; y=y0; context.moveTo(x,y);
x+=xx; y+=0; context.moveTo(x,y);
x+=xx; y+=0; context.lineTo(x,y);
x+=xx; y+=yy; context.lineTo(x,y);
x+=(xx*-1); y+=yy; context.lineTo(x,y);
x+=(xx*-1); y+=0; context.lineTo(x,y);
x+=(xx*-1); y+=(yy*-1); context.lineTo(x,y);
x+=xx; y+=(yy*-1); context.lineTo(x,y);
context.fillStyle = "#FFFF99";
context.fill();
context.strokeStyle = "rgba(0,0,0,1)";
context.stroke();
}
function isEven(n)
{
return parseFloat(n) && (n % 2 == 0);
}
</script>
</section>
</body>
I have marked the HexagonObj creation that works and that dose not work.
You need to declare x and y as variables in each function where they are used. Because you are missing the var declaration, the functions are all accessing global x and y variables. As a consequence, the first call to HexagonObj clobbers the loop variables in main_init().
(Technically, you only need to declare var x, y in one of the functions to solve the immediate problem. However, it's bad form to be using global variables like that.)
for loop executing only once in function main_init since x and y which are global are modified inside HexagonObj function to y:81 and x:50
Related
This is the effect that I am trying to achieve: link
I have gotten the four waves and they are indeed animated, but I have gotten stuck on giving each of them a slightly different animation. At the current point, all curves move at the same speed, in the same direction and switch at the same place too. they should vary slightly in all these aspects. The end result I am looking for is very much like the link i posted, with difference that each wave can only have a maximum of one cycle, that is going up once and coming down once. Thank you for your input.
Below is my code:
function start() {
var canvas = $("canvas");
console.log(canvas);
canvas.each(function(index, canvas) {
var context = canvas.getContext("2d");
canvas.width = $(".box").eq(index).width();
canvas.height = $(".box").eq(index).height();
context.clearRect(0, 0, canvas.width, canvas.height);
drawCurves(context, step);
step += 1;
});
requestAnimationFrame(start);
}
var step = -1;
function drawCurves(ctx, step) {
var width = ctx.canvas.width;
var height = ctx.canvas.height;
ctx.lineWidth = 2;
for (i = 0; i < 4 ; i++) {
var x = 0;
var y = 0;
ctx.beginPath();
if (i === 0 ) {
ctx.strokeStyle = "red";
var amplitude = 20;
var frequency = height / (2 * Math.PI) ;
console.log(i, frequency);
} if ( i === 1) {
ctx.strokeStyle = "blue";
var amplitude = 30;
var frequency = (height / (2 * Math.PI));
console.log(i, frequency);
} if ( i === 2) {
ctx.strokeStyle = "green";
var amplitude = 40;
var frequency = height / (2 * Math.PI) ;
console.log(i, frequency);
} if (i === 3) {
ctx.strokeStyle = "yellow";
var amplitude = 50;
var frequency = height / (2 * Math.PI) ;
console.log(i, frequency);
}
ctx.save();
ctx.translate(-amplitude * Math.sin(step / frequency), 0);
while (y < height) {
x = (width / 2) + (amplitude * Math.sin((y + step) / frequency)) ;
ctx.lineTo(x, y);
y++;
}
ctx.closePath();
ctx.stroke();
ctx.restore();
}
}
$(document).ready(function() {
start();
})
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="box">
<canvas id="canvas"></canvas>
</div>
<div class="box">
<canvas id="canvas"></canvas>
</div>
</body>
</html>
And here a Code Pen
Your code draw only one sinus wave.
I'll advice you those points:
_If you want different(simultaneaous) wave you've to use differents x/y values at the draw point.
_You use $(document).ready(function() as animation loop, that's not the better way do do it. For animation you should set a setInterval or way better use the requestAnimationFrame who is meant to create animation. In each animation loop draw the 4 sinus lines, i'll forget about step for using objects instead that i think is better but that's not important point. I've no time to try your code but what is it doing when using requestAnimationFrame(start()) instead of the $document.ready ?
Obviously in each animatve to clear the drawing place using clearRect(width,height); for example.
_The 4 steps add +1 to +4 to y in the same cartesian equation. In a sinus curve that will not really be seeing by human eyes because it's a really slight variation. You can use differents equations using differents sinusoïd equations for each step/object, i.e. Math.sin(y)+10 or Math.sin(y)*10 etc...or even different incremantation value for each differents objects.
_i'll avoid translate and use a for loop to increment the x value and get the y value using sin(x) and whatever equation you need , that's personal choice but will avoid to write the .translate() line and will use normal coordinates instead of moved coordinates so you'll easily see in console.log real coordinates in canvas area.
_As for previous you can throw away the checking IFs at beginning of program if you use objets in a array (and loop it) and set a styleColor and weight of each of 4 objets.
Hope it's help, no time to write a clean code.
#enxaneta thank you for your input! Got it the way I wanted to, below is my solution:
var step = 0;
function start(timestamp) {
var canvas = $("canvas");
canvas.each(function(index, canvas) {
var context = canvas.getContext("2d");
canvas.width = $(".box").eq(index).width();
canvas.height = $(".box").eq(index).height();
context.clearRect(0, 0, canvas.width, canvas.height);
if (canvas.height > 1000 ) {
drawWave(context, 20,"sin");
drawWave(context, 60,"cos");
drawWave(context, 40,"sin");
drawWave(context, 80,"cos");
}
if (canvas.height < 1000 ) {
drawWave(context, 10,"sin");
drawWave(context, 30,"cos");
drawWave(context, 20,"sin");
drawWave(context, 40,"cos");
}
step = timestamp / 7;
});
window.requestAnimationFrame(start);
}
function drawWave(ctx,amplitude,trig){
var width = ctx.canvas.width;
var height = ctx.canvas.height;
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle = "blue";
var x = 0;
var y = 0;
var frequency = height / (2 * Math.PI);
ctx.save();
ctx.translate(-amplitude * Math[trig](step / frequency), 0);
while (y < height) {
x = width / 2 + amplitude * Math[trig]((y + step) / frequency);
ctx.lineTo(x, y);
y++;
}
// ctx.closePath();
ctx.stroke();
ctx.restore();
}
$(document).ready(function() {
start();
});
canvas {
background-color: wheat;
position: absolute;
}
.box {
width: 500px;
height: 2000px;
border: solid;
}
.box.t {
width: 500px;
height: 200px;
border: solid;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="box t">
<canvas id="canvas"></canvas>
</div>
<div class="box">
<canvas id="canvas"></canvas>
</div>
</body>
</html>
I am trying to create a game (at beginning stages). I am trying to create balls that bounce around a canvas, I have created balls, randomized them and have animated them.
But when trying to add a boundary I can only seem to get the balls to act as one object rather than separate ones. If NumShapes is changed to 1 it works perfectly.
if( shapes[i].x<0 || shapes[i].x>width) dx=-dx;
if( shapes[i].y<0 || shapes[i].y>height) dy=-dy;
For movement:
shapes[i].x+=dx;
shapes[i].y+=dy;
See this:
var ctx;
var numShapes;
var shapes;
var dx = 5; // speed on the X axis
var dy = 5; // speed on the Y axis
var ctx = canvas.getContext('2d');
var width = canvas.width;
var height = canvas.height;
function init() // draws on the Canvas in the HTML
// calling functions here would not run them in the setInterval
{
numShapes = 10;
shapes = [];
drawScreen();
ctx = canvas.getContext('2d');
setInterval(draw, 10); // Runs the Draw function with nestled functions
makeShapes();
}
function draw() {
clear();
drawShapes();
}
function clear() {
ctx.clearRect(0, 0, width, height); // clears the canvas by WIDTH and HEIGHT variables
}
function makeShapes() {
var i;
var tempRad;
var tempR;
var tempG;
var tempB;
var tempX;
var tempY;
var tempColor;
for (i = 0; i < numShapes; i++) { // runs while i is less than numShapes
tempRad = 10 + Math.floor(Math.random() * 25); // random radius number
tempX = Math.random() * (width - tempRad); // random X value
tempY = Math.random() * (height - tempRad); // random Y value
tempR = Math.floor(Math.random() * 255); // random red value
tempG = Math.floor(Math.random() * 255); // random green value
tempB = Math.floor(Math.random() * 255); // random blue value
tempColor = "rgb(" + tempR + "," + tempG + "," + tempB + ")"; // creates a random colour
tempShape = {
x: tempX,
y: tempY,
rad: tempRad,
color: tempColor
}; // creates a random shape based on X, Y and R
shapes.push(tempShape); // pushes the shape into the array
}
}
function drawShapes() {
var i;
for (i = 0; i < numShapes; i++) {
ctx.fillStyle = shapes[i].color;
ctx.beginPath();
ctx.arc(shapes[i].x, shapes[i].y, shapes[i].rad, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();
shapes[i].x += dx; // increases the X value of Shape
shapes[i].y += dy; // increases the Y value of Shape
// Boundary, but applies to all shapes as one shape
if (shapes[i].x < 0 || shapes[i].x > width) dx = -dx;
if (shapes[i].y < 0 || shapes[i].y > height) dy = -dy;
}
}
function drawScreen() {
//bg
ctx.fillStyle = '#EEEEEE';
ctx.fillRect(0, 0, width, height);
//Box
ctx.strokeStyle = '#000000';
ctx.strokeRect(1, 1, width - 2, height - 2);
}
canvas {
border: 1px solid #333;
}
<body onLoad="init();">
<div class="container container-main">
<div class="container-canvas">
<canvas id="canvas" width="800" height="600">
This is my fallback content.
</canvas>
</div>
</div>
</body>
Your dx and dy are globals, they should be unique for each ball object that you are simulating. Either clear them to 0 in your rendering loop (draw) or actually implement a ball object/class to hold variables unique to that object.
When you do your collision detection you change dx and dy which then persists to the next ball object as they are global.
Your fiddle, edited to add local dx and dy per shape: https://jsfiddle.net/a9b3rm5u/3/
tempDx = Math.random()*5; // random DX value
tempDy = Math.random()*5; // random DY value
shapes[i].x+=shapes[i].dx;// increases the X value of Shape
shapes[i].y+=shapes[i].dy;// increases the Y value of Shape
if( shapes[i].x<0 || shapes[i].x>width) shapes[i].dx= - shapes[i].dx;
if( shapes[i].y<0 || shapes[i].y>height) shapes[i].dy= -shapes[i].dy;
I've been working on a chunk of code for a would-be Sierpinski fractal animation, but for some reason, the animation part just doesn't seem to work. I also tried using setInterval(), with the same results, namely a blank canvas. The idea is to draw an equilateral triangle with vertex coordinates as parameters step by step, as though somebody was drawing it on a piece of paper. Could you have a look to see what's wrong with it?
On a side note, I've copied a few examples of canvas animation off a few web tutorials, and none of them appear to be working in my files either. I use Firefox and Chrome, both up to date, so I guess it's not a technical issue.
<!DOCTYPE html>
<style>
canvas {
width: 600px;
height: 600px;
text-align: center;
background-color: white;
background-position: center;
position: relative;
top: 0px;
left: 0px;
border:1px solid #d3d3d3;
}
<body>
<canvas id="sCanvas"></canvas>
<script>
This is where the animation is supposed to take place; draws a line from (Ax,Ay) to (Bx,By).
function lineAnimation(x1,y1,x2,y2,ctx) {
var deltaX = (x2 - x1) / 100;
var deltaY = (y2 - y1) / 100;
var x = x1;
var y = y1;
var timer = setInterval(function () {
ctx.moveTo(x,y);
ctx.lineTo(x+deltaX,y+deltaY);
ctx.stroke();
x += deltaX;
y += deltaY;
}, 100);
if ((x===x2) && (y===y2)) clearTimeout(timer);
}
function drawTriangle(Ax,Ay,Bx,By,Cx,Cy,ctx) {
lineAnimation(Ax,Ay,Bx,By,ctx);
lineAnimation(Bx,By,Cx,Cy,ctx);
lineAnimation(Cx,Cy,Ax,Ay,ctx);
}
function init() {
var canvas=document.getElementById("sCanvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
drawTriangle(10,10,30,50,50,10);
}
init();
</script>
Your functions are requiring the parameter ctx which you didn't include, as such they don't know what ctx is. All you need to do is include it in drawTriangle():
drawTriangle(10,10,30,50,50,10,ctx);
And then everything works.
Try This
function lineAnimation(x1,y1,x2,y2,ctx) {
var deltaX = (x2 - x1) / 100;
var deltaY = (y2 - y1) / 100;
var x = x1;
var y = y1;
var timer = setInterval(function () {
var canvas=document.getElementById("sCanvas"); //Added Change
var ctx = canvas.getContext("2d"); //Added Change
ctx.moveTo(x,y);
ctx.lineTo(x+deltaX,y+deltaY);
ctx.stroke();
x += deltaX;
y += deltaY;
}, 100);
if ((x===x2) && (y===y2)) clearTimeout(timer);
}
function drawTriangle(Ax,Ay,Bx,By,Cx,Cy,ctx) {
lineAnimation(Ax,Ay,Bx,By,ctx);
lineAnimation(Bx,By,Cx,Cy,ctx);
lineAnimation(Cx,Cy,Ax,Ay,ctx);
}
function init() {
var canvas=document.getElementById("sCanvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
drawTriangle(10,10,30,50,50,10);
}
init();
It is giving you an error over ctx.moveTo(x,y); and ctx.lineTo(x+deltaX,y+deltaY); because thet are not able to use you ctx which is basically an object of your canvas. so just try to add them in code and things will work fine
DEMO
I've been trying to put together a simple maze game using HTML5 and Javascript. I can successfully load the HTML and CSS content onto the page, but no matter what I try, I can't get the JS to load. It's definitely saved as a .html file and i've only been using Sublime text to put it together (but I wouldn't have thought that would have an affect anyway). Just a bit stumped really, so I thought it must be something I've missed in my code. I wasn't sure if I've missed something?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title> Maze Game </title>
</head>
<style>
canvas {
border: 8px double navy;
background: white;
}
img {
display: none;
}
button {
padding: 3px;
}
</style>
<body>
<canvas id="canvas"> </canvas>
<img id="sprite" src="sprite.png">
<script>
//these define the global variables for the canvas and the drawing context
var canvas;
var context;
var x = 0;
var y = 0; //positioning of the sprite
var dx = 0;
var dy = 0; //momentum of the sprite at start
window.onload = function() {
//setting up the canvas
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
//Draws the maze background
drawMaze("maze.png", 268, 5);
//On key press, run the following function
window.onkeydown = processKey;
};
var x = 0;
var y = 0;
function drawMaze(mazeFile, Xstart, Ystart) {
//This loads the maze picture in
dx = 0;
dy = 0; //if the face is already moving, stop it
var imgMaze = new Image();
imgMaze.onLoad = function() {
canvas.width = imgMaze.width;
canvas.height = imgMaze.height;
//Draws the maze onto the canvas
context.drawImage(imgMaze, 0, 0);
//draws the sprite and positions
x = Xstart;
y = Ystart;
var imgSprite = document.getElementById("sprite");
context.drawImage(imgSprite, x, y);
context.stroke();
//sets a short timer for the next frame to be drawn in (10ms)
setTimeout("drawFrame()", 10);
};
imgMaze.src = mazeFile;
}
function processKey(e) { //e needs to be used for event handling
//stop the sprite if it's already moving - enables collision
var dx = 0;
var dy = 0;
//condition for the Up arrow being pressed
if (e.keyCode == 38) {
dy = -1;
}
//condition for the Left arrow being pressed
if (e.keyCode == 37) {
dx = -1;
}
//condition for the Down arrow being pressed
if (e.keyCode == 40) {
dy = 1;
}
//condition for the Right arrow being pressed
if (e.keyCode == 39) {
dx = 1;
}
}
function drawFrame() {
if (dx != 0 || dy != 0) {
context.beginPath();
context.fillStyle = "rgb(254,244,207)";
context.rect(x, y, 15, 15);
context.fill
x += dx;
y += dy;
if (checkForCollision()) {
(dx/y = 0)
x -= dx;
y -= dy;
dx = 0;
dy = 0;
}
//Now we can finally draw the sprite!
var imgSprite = document.getElementById("sprite");
context.drawImage(imgSprite, x, y);
if (y > (canvas.height - 17)) {
alert("Congratulations! You made it!");
return;
}
}
timer = setTimeout(drawFrame, 10);
}
var imageData = context.getImageData(0, 0, 100, 50);
var pixels = imageData.data;
for (var i = 0, n = pixels.length; i < n; i += 4) {
//This will get the data/values for one pixel
var red = pixels[i];
var green = pixels [i+1];
var blue = pixels [i+2];
var alpha = pixels [i+3];
//This will invert the colours
pixels[i] = 255 - red;
pixels[i+1] = 255 - green;
pixels[i+2] = 255 - blue;
}
context.putImageData(imageData, 0, 0);
function checkForCollision() {
var imgData = context.getImageData(x-1, y-1, 15+2, 15+2);
var pixels = imgData.data;
//Then we need to perform a check, same as above
for (var i = 0; n = pixels.length, i < n; i += 4) {
var red = pixels[i];
var green = pixels[i+1];
var blue = pixels[i+2];
var alpha = pixels[i+3];
//now check for the black pixels for a wall
if (red == 0 && green == 0 && blue == 0) {
return true;
} //checks for a greyish colour - possibly the edge of a wall
if (red == 169 && green == 169 && blue == 169) {
return true;
}
}
return false; //there was no collision
}
</script>
</body>
</html>
There are lots of errors in this code. For example, in this section alone:
(commented where some issues are)
function drawFrame() {
if (dx != 0 || dy != 0) {
context.beginPath();
context.fillStyle = "rgb(254,244,207)";
context.rect(x, y, 15, 15);
context.fill // Missing parentheses and semicolon
x += dx;
y += dy;
if (checkForCollision()) {
(dx/y = 0) // Equivalent to { dx / (y = 0) }
x -= dx; // which both serves no purpose and divides by zero
y -= dy;
dx = 0;
dy = 0;
}
//Now we can finally draw the sprite!
var imgSprite = document.getElementById("sprite");
context.drawImage(imgSprite, x, y);
if (y > (canvas.height - 17)) {
alert("Congratulations! You made it!");
return;
}
}
timer = setTimeout(drawFrame, 10); // timer is not defined anywhere
// also you are calling the function within itself
// with no end condition, so it's an infinite loop
}
And on line 48:
setTimeout("drawFrame()", 10);
You should be passing the function as just the function identifier, not as a string. As such:
setTimeout(drawFrame, 10);
These are just a few. There are also some logical errors, variables that are defined but never used, and more. In its current state this will not compile.
Also, if only just for clarity's sake, try to define a script type instead of just leaving the tag empty, like:
<script type="text/javascript">
// Some JS
</script>
It can be hard when you've been staring at code for hours, but it helps to give each section a slow read-through and think about exactly what the code is doing. You can avoid lots of syntactical and logical errors this way.
I also recommend using a text editor or online interface (JS Bin, JSfiddle, etc.) that has JShint/lint or some kind of code-checking functionality. You can even use http://www.javascriptlint.com/online_lint.php and paste your whole code in there.
I'm trying to animate a sine wave in JS but it's not acting as expected. I'm using a <canvas> element along with window.requestAnimationFrame() method but it's a CPU hog and as i change frequency with the slider it just break and show random waveforms. I also don't know if drawing adjacent lines is the best way to represent a sine wave. Please note that i'll use vanilla JS and that the sine's frequency and amplitude are variables set by sliders. Thanks in advance.
This is what i got so far: http://cssdeck.com/labs/8cq5vclp
UPDATE: i worked on it and this is the new version: http://cssdeck.com/labs/sbfynjkr
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d"),
cHeight = canvas.height,
cWidth = canvas.width,
frequency = document.querySelector("#f").value,
amplitude = 80,
x = 0,
y = cHeight / 2,
point_y = 0;
window.onload = init;
function init() {
document.querySelector("#f").addEventListener("input", function() {
frequency = this.value;
document.querySelector("#output_f").value = frequency;
}, false);
drawSine();
}
function drawSine() {
ctx.clearRect(0, 0, cWidth, cHeight);
ctx.beginPath();
ctx.moveTo(0, y);
ctx.strokeStyle = "red";
ctx.lineTo(cWidth, y);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.strokeStyle = "black";
for (x = 0; x < 600; x++) {
point_y = amplitude * -Math.sin((frequency / 95.33) * x) + y;
ctx.lineTo(x, point_y);
}
ctx.stroke();
ctx.closePath();
requestAnimationFrame(drawSine);
}
canvas {
border: 1px solid red;
margin: 10px;
}
<input id="f" type="range" min="0" max="20000" value="20" step="1">
<output for="f" id="output_f">20</output>
<canvas width="600px" height="200px"></canvas>
I've messed around with sine waves quite a bit, because I'm working on a little project that involves animated sine waves. I've got some code you might be interested in taking a look at. Like mentioned earlier, you need to make sure you are using the right increment in your loop so the lines do not look jagged.
https://jsfiddle.net/uawLvymc/
window.requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(f) {
return setTimeout(f, 1000 / 60)
};
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var startTime = new Date().getTime();
function getPath(height) {
var width = canvas.width;
var spacing = 0.08;
var loopNum = 0;
var pointList = [];
var i = 0;
for (i = 0; i < width / 2; i++) {
pointList[loopNum] = [loopNum, Math.sin(loopNum * spacing) * (i * height) + 100];
loopNum++;
}
for (i = width / 2; i > 0; i--) {
pointList[loopNum] = [loopNum, Math.sin(loopNum * spacing) * (i * height) + 100];
loopNum++;
}
return pointList;
}
function draw() {
var currentTime = new Date().getTime();
var runTime = currentTime - startTime;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle = "rgb(80, 100, 230)";
var height = Math.sin(runTime * 0.008) * 0.2;
var pointList = getPath(height);
for (var i = 0; i < 500; i++) {
if (i === 0) {
ctx.moveTo(pointList[0][0], pointList[0][1]);
} else {
ctx.lineTo(pointList[i][0], pointList[i][1]);
}
}
ctx.stroke();
window.requestAnimationFrame(draw);
}
window.requestAnimationFrame(draw);
Sorry I didn't really edit down the code, it's just a direct copy from what I was working on. Hope it helps though.
See if this example could help you a little
Sine Wave Example canvas
function init()
{
setInterval(OnDraw, 200);
}
var time = 0;
var color = "#ff0000";
function OnDraw()
{
time = time + 0.2;
var canvas = document.getElementById("mycanvas");
var dataLine = canvas.getContext("2d");
var value = document.getElementById("lineWidth");
dataLine.clearRect(0, 0, canvas.width, canvas.height);
dataLine.beginPath();
for(cnt = -1; cnt <= canvas.width; cnt++)
{
dataLine.lineTo(cnt, canvas.height * 0.5 - (Math.random() * 2 + Math.cos(time + cnt * 0.05) * 20 ));
}
dataLine.lineWidth = value.value * 0.1;
dataLine.strokeStyle = color;
dataLine.stroke();
}