console.log() keeps running infinitely even after the program finishes execution - javascript
I have an ECG program which plots ECG after taking values from arrays. Upon opening the console (By pressing the f12 button) in Firefox, it shows that the log keeps on writing infinitely even after all the 12 graphs are constructed. It is not supposed to happen! There are 12 arrays each with 1250 elements. I'm giving one array because of the word limit here. Clicking "Click Me" button plots the graph using canvas. Please take the values given at bottom of the question for reference. Please help me find why this overflow is happening. I'm a beginner.
Code:
<!doctype html>
<html>
<head>
<script>
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
window.addEventListener('load', onLoadd, false);
var YRatio=0.75;
var nPointsPerFrame = 10;//This value determines the speed. Higher value means more speed.
var Lead_1 = [];
function onLoadd(evt)
{
drawBkg(byId('canvas'), 3.78, "0.35", "black");
}
function onDocLoaded(evt)
{
//Markings();
drawcurFrame_Lead_1.apply(this, Lead_1);
}
function drawBkg(canvasElem, squareSize, minorLineWidthStr, lineColStr)
{
var nLinesDone = 0;
var i, curX, curY;
var ctx = canvasElem.getContext('2d');
ctx.clearRect(0,0,canvasElem.width,canvasElem.height);
// draw the vertical lines
curX=0;
ctx.strokeStyle = lineColStr;
while (curX < canvasElem.width)
{
ctx.lineWidth = minorLineWidthStr;
ctx.beginPath();
ctx.moveTo(curX, 0);
ctx.lineTo(curX, canvasElem.height);
ctx.stroke();
curX += squareSize;
nLinesDone++;
}
// draw the horizontal lines
curY=0;
nLinesDone = 0;
while (curY < canvasElem.height)
{
ctx.lineWidth = minorLineWidthStr;
ctx.beginPath();
ctx.moveTo(0, curY);
ctx.lineTo(canvasElem.width, curY);
ctx.stroke();
curY += squareSize;
nLinesDone++;
}
}
//FIRST GRAPH Lead_1
// position that will be treated as 0,0 when drawing our points.
var originX_Lead_1=46;
var originY_Lead_1=16;
function Draw_Lead_1(nSamplesToDraw, firstSample, lineWidthStr, lineColourStr)
{
var can = byId('canvas');
var ctx = can.getContext('2d');
ctx.strokeStyle = lineColourStr;
ctx.lineWidth = lineWidthStr;
console.log(firstSample);
ctx.beginPath();
ctx.moveTo( originX_Lead_1+(firstSample*0.377), originY_Lead_1+(Lead_1[firstSample-1]*YRatio) );
for (i=0; i<nSamplesToDraw; i++)
{
var curSample = Lead_1[i + firstSample];// calculate y coordinate
ctx.lineTo( originX_Lead_1+((firstSample+i)*0.377), originY_Lead_1+(curSample*YRatio) );
}
ctx.stroke();
}
var curFrame_Lead_1=0;//Starts with frame 0.
function drawcurFrame_Lead_1()
{
Draw_Lead_1(nPointsPerFrame, nPointsPerFrame*curFrame_Lead_1, "0.75", "blue");//Calling function to draw the graph
curFrame_Lead_1+=1;//Frame is incremented one by 1.
requestAnimationFrame( drawcurFrame_Lead_1 );
}
</script>
</head>
<body>
<div id='txt'></div>
<canvas id="canvas" width="1250" height="800"></canvas>
<button onclick="onDocLoaded()">Click Me</button>
</body>
</html>
Lead_1 = [69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,72,72,72,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,72,72,73,73,73,73,73,73,73,73,73,72,72,72,72,72,72,72,71,71,71,70,69,69,68,67,67,67,67,68,68,69,69,70,71,72,72,73,73,73,73,73,73,73,73,73,72,72,73,73,73,73,73,72,72,73,76,79,81,80,75,67,55,44,36,34,38,46,57,67,74,77,77,76,74,73,72,73,73,73,73,73,73,73,74,74,74,74,73,73,73,73,73,73,73,73,73,73,73,73,73,73,74,73,73,72,71,70,69,68,68,67,66,66,65,64,63,63,62,61,61,61,61,61,61,61,61,61,62,62,63,64,64,65,66,67,68,69,70,71,71,72,73,73,73,73,73,73,73,73,73,74,74,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,72,73,73,74,74,73,73,72,72,72,72,73,73,73,72,72,72,72,72,73,73,73,72,72,72,72,73,73,72,72,72,71,70,69,69,69,68,67,67,67,67,67,67,68,69,69,70,71,71,72,73,73,73,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,73,75,78,80,78,72,62,51,40,34,33,39,49,59,69,75,77,77,75,73,72,72,72,72,73,73,73,72,72,72,73,73,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,71,71,71,70,70,69,68,67,66,65,64,64,64,63,63,62,61,61,60,60,60,60,60,60,60,61,61,62,62,63,64,65,66,67,67,68,69,70,71,71,72,72,72,72,72,72,72,73,73,73,73,72,72,72,72,72,72,72,72,72,73,73,73,73,73,73,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,71,70,70,69,69,68,68,67,67,66,66,66,67,67,68,69,70,71,71,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,74,76,79,80,77,70,60,49,39,33,33,40,50,61,70,75,77,76,75,73,72,72,72,73,73,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,73,72,72,71,70,69,69,68,67,66,65,64,64,63,62,62,61,60,60,60,60,61,61,61,61,61,61,62,62,63,64,65,66,67,68,69,69,70,71,72,73,73,73,73,73,73,73,73,73,73,73,72,73,73,73,73,73,73,72,72,72,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,72,72,72,73,73,73,73,72,72,72,72,73,73,73,72,72,71,70,70,69,68,68,67,67,67,67,67,67,68,68,69,69,70,70,71,72,72,72,72,72,72,72,73,73,73,73,72,72,72,72,72,72,72,73,74,77,79,79,76,68,57,45,36,33,36,44,54,64,72,76,77,76,75,73,72,72,72,73,73,73,73,73,72,72,72,72,72,72,72,72,73,73,73,73,73,73,73,73,72,73,73,73,72,72,71,70,69,68,68,67,66,65,64,63,62,62,62,61,61,61,60,60,61,61,61,61,62,62,63,63,64,64,65,66,67,68,69,69,70,71,72,72,72,73,73,73,73,73,73,73,72,72,72,72,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,73,73,73,73,73,73,72,72,72,72,73,73,72,72,72,72,72,73,73,73,72,72,72,72,72,72,72,72,72,71,70,69,68,68,67,67,67,66,66,67,67,68,69,70,70,71,71,72,72,72,72,72,72,72,72,73,72,72,72,72,72,72,72,72,71,72,74,77,79,78,74,66,55,44,36,33,36,44,55,65,72,76,77,76,74,73,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,71,71,71,70,70,69,68,67,66,65,64,64,63,63,62,61,61,60,60,60,60,60,60,60,61,61,62,62,63,63,64,65,66,67,67,68,69,70,71,72,73,73,72,72,72,72,72,72,73,73,73,73,72,72,72,73,73,72,72,72,72,72,72,72,73,73,72,72,72,72,72,73,73,73,73,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,72,71,70,70,69,68,68,67,67,67,67,67,67,68,68,69,70,70,71,72,72,72,72,72,72,72,72,72,72,72,72,72,72,73,72,72,72,72,73,76,79,80,79,73,64,52,41,34,34,39,49,59,69,75,77,77,76,74,73,73,73,73,73,73,73,73,73,73,73,73,73,74,74,73,73,73,73,73,73,74,74,74,74,74,74,74,74,73,72,71,70,69,68,68,67,67,66,65,64,64,64,63,63,63,62,62,62,62,63,63,63,63,64,64,65,66,66,67,68,69,71,72,72,73,74,75,75,75,76,76,76,74,72,70,70,69,69];
It is because you are calling drawcurFrame_Lead_1 in requestAnimationFrame. You have to put condition to finish the execution of program in drawcurFrame_Lead_1
Update
var flag= 0;
function drawcurFrame_Lead_1()
{
if(flag ==0)
{
Draw_Lead_1(nPointsPerFrame, nPointsPerFrame*curFrame_Lead_1, "0.75", "blue");//Calling function to draw the graph
curFrame_Lead_1+=1;//Frame is incremented one by 1.
requestAnimationFrame( drawcurFrame_Lead_1 );
}
}
I have declared a variable flag = 0;
Now what you can do is set flag to 1 whenever your program is finished
Related
Make identical objects move independently in Javascript Canvas
So I am trying to make a simple space game. You will have a ship that moves left and right, and Asteroids will be generated above the top of the canvas at random X position and size and they will move down towards the ship. How can I create Asteroid objects in seperate positions? Like having more than one existing in the canvas at once, without creating them as totally seperate objects with seperate variables? This sets the variables I would like the asteroid to be created on. var asteroids = { size: Math.floor((Math.random() * 40) + 15), startY: 100, startX: Math.floor((Math.random() * canvas.width-200) + 200), speed: 1 } This is what I used to draw the asteroid. (It makes a hexagon shape with random size at a random x coordinate) function drawasteroid() { this.x = asteroids.startX; this.y = 100; this.size = asteroids.size; ctx.fillStyle = "#FFFFFF"; ctx.beginPath(); ctx.moveTo(this.x,this.y-this.size*0.5); ctx.lineTo(this.x+this.size*0.9,this.y); ctx.lineTo(this.x+this.size*0.9,this.y+this.size*1); ctx.lineTo(this.x,this.y+this.size*1.5); ctx.lineTo(this.x-this.size*0.9,this.y+this.size*1); ctx.lineTo(this.x-this.size*0.9,this.y); ctx.fill(); } I included ALL of my code in this snippet. Upon running it, you will see that I currently have a ship that moves and the asteroid is drawn at a random size and random x coordinate. I just need to know about how to go about making the asteroid move down while creating other new asteroids that will also move down. Thank You for all your help! I am new to javascript. // JavaScript Document ////// Variables ////// var canvas = {width:300, height:500, fps:30}; var score = 0; var player = { x:canvas.width/2, y:canvas.height-100, defaultSpeed: 5, speed: 10 }; var asteroids = { size: Math.floor((Math.random() * 40) + 15), startY: 100, startX: Math.floor((Math.random() * canvas.width-200) + 200), speed: 1 } var left = false; var right = false; ////// Arrow keys ////// function onkeydown(e) { if(e.keyCode === 37) { left = true; } if(e.keyCode === 39) { right = true; } } function onkeyup(e) { if (e.keyCode === 37) { left = false; } if(e.keyCode === 39) { right = false; } } ////// other functions ////// //function to clear canvas function clearCanvas() { ctx.clearRect(0,0,canvas.width,canvas.height); } // draw the score in the upper left corner function drawscore(score) { var score = 0; ctx.fillStyle = "#FFFFFF"; ctx.fillText(score,50,50); } // Draw Player ship. function ship(x,y) { var x = player.x; var y = player.y; ctx.fillStyle = "#FFFFFF"; ctx.beginPath(); ctx.moveTo(x,y); ctx.lineTo(x+15,y+50); ctx.lineTo(x-15,y+50); ctx.fill(); } // move player ship. function moveShip() { document.onkeydown = onkeydown; document.onkeyup = onkeyup; if (left === true && player.x > 50) { player.x -= player.speed; } if (right === true && player.x < canvas.width - 50) { player.x += player.speed; } } // Draw Asteroid function drawasteroid() { this.x = asteroids.startX; this.y = 100; this.size = asteroids.size; ctx.fillStyle = "#FFFFFF"; ctx.beginPath(); ctx.moveTo(this.x,this.y-this.size*0.5); ctx.lineTo(this.x+this.size*0.9,this.y); ctx.lineTo(this.x+this.size*0.9,this.y+this.size*1); ctx.lineTo(this.x,this.y+this.size*1.5); ctx.lineTo(this.x-this.size*0.9,this.y+this.size*1); ctx.lineTo(this.x-this.size*0.9,this.y); ctx.fill(); } // move Asteroid function moveAsteroid() { //don't know how I should go about this. } // update setInterval (update, 1000/canvas.fps); function update() { // test collisions and key inputs moveShip(); // redraw the next frame of the animation clearCanvas(); drawasteroid(); drawscore(); ship(); } <!doctype html> <html> <head> <meta charset="UTF-8"> <title>My Game</title> <script src="game-functions.js"></script> <!-- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> --> </head> <body> <canvas id="ctx" width="300" height="500" style="border: thin solid black; background-color: black;"></canvas> <br> <script> ////// Canvas setup ////// var ctx = document.getElementById("ctx").getContext("2d"); </script> </body> </html>
You want to make the creation of asteroids dynamic...so why not set up a setInterval that gets called at random intervals as below. You don't need a separate declaration for each Asteroids object you create. You can just declare a temporary one in a setInterval function. This will instantiate multiple different objects with the same declaration. Of course you need to store each object somewhere which is precisely what the array is for. You also have to make sure that asteroids get removed from the array whenever the moveAsteroid function is called if they are off of the canvas. The setInterval function below should be called on window load and exists alongside your main rendering setInterval function. You are also going to have to change your moveAsteroid function a bit to be able to point to a specific Asteroids object from the array. You can do this by adding the Asteroids object as a parameter of the function or by making the function a property of the Asteroids class and using this. I did the latter in the example below. var astArray = []; var manageAsteroidFrequency = 2000; var Asteroids { X: //something Y://something speed:1 move: function() { this.X -= speed; } } var mainRenderingFunction = setInterval( function() { for (var i = astArray.length-1 ; i > -1; i --){ if(astArray[i].Y < 0){ astArray.splice(i, 1) }else{ astArray[i].move; } } }, 40); var manageAsteroids = setInterval( function () { if (astArray.length < 4){ var tmpAst = new Asteroids(); astArray.push(tmpAst); } manageAsteroidFrequency = Math.floor(Math.random()*10000); }, manageAsteroidFrequency);
How to make javascript canvas draw faster?
I have the following code to display an ECG. I use the canvas to draw the graph background (each grid of 2.5 mm dimension). Later I'm taking the y coordinates from an array array_1 (x coordinates are calculated within the program). The problem with this approach is it will take around 40 seconds to plot the entire graph since there are 1250 values within array array_1. What I could do is I could do the plotting part within a loop in which case, the entire graph is plotted as soon as the page is loaded. But, I need the plotting to happen over the course of 5 seconds. Not more. Not less. How would I alter the code to do this? Please help. <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <canvas id="canvas" width="1350" height="1300" style="background-color: white;"></canvas> <script type='text/javascript'> var canvas = document.getElementById("canvas"); var ctxt = canvas.getContext("2d"); var n1 = 1; var n1_x=49; //Graph x coordinate starting pixel. var n1_y=72;//Graph y coordinate starting pixel. var array_1 = []// array from which y coordinates are taken. Has 1250 elements var ctx = canvas.getContext("2d"); var x=0; var y=0; var Line_position=-1; while(x<=1350)//graph width { ctxt.lineWidth = "0.5"; Line_position=Line_position+1; if(Line_position%5==0) { ctxt.lineWidth = "1.5"; } ctxt.strokeStyle = "black"; ctxt.beginPath(); ctxt.moveTo(x, 0); ctxt.lineTo(x, 1300); ctxt.stroke(); x=x+9.43; } Line_position=-1; while(y<=1300)//graph height { ctxt.lineWidth = "0.5"; Line_position=Line_position+1; if(Line_position%5==0) { ctxt.lineWidth = "1.5"; } ctxt.strokeStyle = "black"; ctxt.beginPath(); ctxt.moveTo(0, y); ctxt.lineTo(1350,y); ctxt.stroke(); y=y+9.43; } drawWave(); function drawWave() { requestAnimationFrame(drawWave); ctx.lineWidth = "1"; ctx.strokeStyle = 'blue'; ctx.beginPath(); ctx.moveTo(n1_x- 1, n1_y+array_1[n1-1]);//move to the pixel position ctx.lineTo(n1_x, n1_y+array_1[n1]);//Draw to the pixel position ctx.stroke(); n1_x=n1_x+0.374;//Incrementing pixel so as to traverse x axis. n1++; } </script> </body> </html> Here is the array: array_1 = [69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,72,72,72,72,72,72,72,73,73,74,74,74,74,74,74,74,73,73,73,73,74,74,74,74,73,73,73,73,73,73,73,73,73,73,73,73,73,74,74,74,73,73,73,72,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,72,71,72,72,72,73,73,73,72,72,72,73,73,73,74,73,73,72,72,72,72,72,73,73,73,73,73,72,72,72,72,73,73,73,72,72,72,71,101,71,70,70,70,69,68,68,67,67,66,66,67,67,69,70,72,72,72,73,73,74,73,73,73,73,73,73,73,73,73,74,76,77,76,70,57,40,22,11,11,22,40,57,69,73,73,71,71,71,72,72,73,73,74,74,74,73,72,72,72,72,72,72,72,72,72,72,72,72,71,71,70,70,71,71,71,71,70,70,69,69,69,69,69,69,69,68,68,68,67,67,66,66,65,65,64,63,63,62,62,62,62,62,62,62,62,63,63,64,65,66,67,68,68,69,70,71,72,72,72,73,73,73,73,72,72,72,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,72,73,73,73,73,72,73,73,73,73,73,73,73,73,73,73,72,72,72,72,72,72,73,73,74,74,74,74,74,74,73,73,72,73,73,73,74,73,73,72,72,72,73,73,73,72,72,73,73,74,74,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,71,70,70,70,70,70,69,69,68,67,67,67,67,68,69,71,72,72,73,73,73,73,74,74,74,74,74,73,73,73,73,75,77,78,76,67,53,35,18,8,10,23,41,58,69,73,72,71,70,71,72,73,73,73,73,73,73,73,73,72,72,73,73,73,73,72,71,71,70,70,71,71,71,71,71,71,71,71,70,70,69,69,69,69,68,68,67,67,67,67,67,66,65,65,65,64,63,62,61,61,61,60,60,60,59,60,60,60,61,62,63,65,66,66,67,68,69,70,71,72,72,72,72,73,73,73,72,72,72,72,72,72,72,73,73,73,73,73,73,72,72,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,71,71,72,72,73,73,73,72,72,72,72,72,72,73,73,73,73,73,73,73,73,73,72,73,73,73,73,73,73,72,73,73,73,73,73,73,73,72,72,72,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,71,71,70,70,69,69,69,68,67,67,66,65,66,66,68,69,70,71,72,72,73,73,73,73,73,73,74,74,74,74,74,74,76,78,78,74,64,48,29,13,5,10,26,45,62,71,73,72,71,71,72,73,73,73,73,73,74,74,74,73,72,72,72,73,73,73,73,73,73,73,72,72,72,72,71,71,71,71,71,71,71,71,71,70,70,69,69,69,69,68,67,66,66,66,66,65,65,64,63,62,62,61,61,60,60,60,60,61,62,62,63,64,65,66,67,68,70,71,72,72,72,72,72,72,73,73,73,73,73,73,73,74,74,75,75,74,74,74,73,73,73,74,73,73,73,73,73,74,74,74,74,74,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,73,73,74,74,74,73,73,73,73,73,73,73,73,73,73,72,72,72,72,73,73,72,72,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,73,73,72,72,71,70,70,70,69,69,68,68,67,67,66,67,67,68,69,70,71,72,73,73,74,74,73,73,73,74,75,75,74,73,73,74,76,78,75,67,52,32,15,5,8,22,41,59,69,73,72,71,70,71,72,72,73,73,73,73,73,73,73,73,73,72,72,72,72,72,72,72,72,72,72,71,71,71,70,70,70,70,70,70,70,69,69,69,69,68,68,68,68,67,67,66,65,65,64,64,64,63,62,61,60,60,60,60,60,61,61,62,62,63,64,65,65,66,67,68,69,70,71,71,71,71,71,71,72,72,73,73,73,72,72,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,72,72,72,72,72,71,71,71,71,71,71,71,72,72,72,72,72,72,72,72,72,71,71,71,72,72,73,73,72,72,72,72,72,73,73,73,73,73,72,72,72,72,72,73,73,73,73,73,72,72,72,73,73,74,73,73,73,73,73,73,73,73,73,73,73,73,72,72,72,72,71,71,71,70,70,70,70,69,69,68,67,67,68,69,71,72,73,73,73,73,73,73,73,73,74,75,75,75,74,74,74,75,77,77,75,67,52,34,18,10,12,26,45,62,71,74,73,72,72,72,73,74,74,74,75,75,74,74,74,74,74,74,74,74,74,73,73,73,73,74,74,73,73,73,73,73,73,73,72,72,71,71,71,71,71,70,70,70,69,69,69,68,68,68,68,67,66,65,64,63,63,62,62,62,63,63,63,63,64,65,66,67,69,69,70,71,72,72,73,73,74,74,74,74,75,75,76,76,74,72,70,70,69,69 ];
I'd probably go about the task something like this. As mentioned in a comment, we need to draw a number of the data-points per-frame. How many we draw depends on the speed that the browser is able to supply an animation frame. I've hard-coded the value to 4, since that seems to work on my machine, but with not much more work you can probably make the code time itself and adjust this value on the fly so that your animation runs for as close as possible to the target time. I had a quick go, but the results were awful, I'll leave that as an exercise in research or thought for the reader. By keeping track of how many frames we've already drawn for the current 'refresh-cycle', we know how far to index into the array for the first point to be drawn for each frame. I've tried to parameterize the code as much as possible, but it's late and I'm tired, I may have overlooked something somewhere. <!doctype html> <html> <head> <script> function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);} window.addEventListener('load', onDocLoaded, false); function onDocLoaded(evt) { drawBkg(byId('canvas'), 9.43, 5, "0.5", "1.5", "black"); drawCurFrame(); } var dataSamples = [69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,72,72,72,72,72,72,72,73,73,74,74,74,74,74,74,74,73,73,73,73,74,74,74,74,73,73,73,73,73,73,73,73,73,73,73,73,73,74,74,74,73,73,73,72,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,72,71,72,72,72,73,73,73,72,72,72,73,73,73,74,73,73,72,72,72,72,72,73,73,73,73,73,72,72,72,72,73,73,73,72,72,72,71,101,71,70,70,70,69,68,68,67,67,66,66,67,67,69,70,72,72,72,73,73,74,73,73,73,73,73,73,73,73,73,74,76,77,76,70,57,40,22,11,11,22,40,57,69,73,73,71,71,71,72,72,73,73,74,74,74,73,72,72,72,72,72,72,72,72,72,72,72,72,71,71,70,70,71,71,71,71,70,70,69,69,69,69,69,69,69,68,68,68,67,67,66,66,65,65,64,63,63,62,62,62,62,62,62,62,62,63,63,64,65,66,67,68,68,69,70,71,72,72,72,73,73,73,73,72,72,72,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,72,73,73,73,73,72,73,73,73,73,73,73,73,73,73,73,72,72,72,72,72,72,73,73,74,74,74,74,74,74,73,73,72,73,73,73,74,73,73,72,72,72,73,73,73,72,72,73,73,74,74,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,71,70,70,70,70,70,69,69,68,67,67,67,67,68,69,71,72,72,73,73,73,73,74,74,74,74,74,73,73,73,73,75,77,78,76,67,53,35,18,8,10,23,41,58,69,73,72,71,70,71,72,73,73,73,73,73,73,73,73,72,72,73,73,73,73,72,71,71,70,70,71,71,71,71,71,71,71,71,70,70,69,69,69,69,68,68,67,67,67,67,67,66,65,65,65,64,63,62,61,61,61,60,60,60,59,60,60,60,61,62,63,65,66,66,67,68,69,70,71,72,72,72,72,73,73,73,72,72,72,72,72,72,72,73,73,73,73,73,73,72,72,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,71,71,72,72,73,73,73,72,72,72,72,72,72,73,73,73,73,73,73,73,73,73,72,73,73,73,73,73,73,72,73,73,73,73,73,73,73,72,72,72,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,71,71,70,70,69,69,69,68,67,67,66,65,66,66,68,69,70,71,72,72,73,73,73,73,73,73,74,74,74,74,74,74,76,78,78,74,64,48,29,13,5,10,26,45,62,71,73,72,71,71,72,73,73,73,73,73,74,74,74,73,72,72,72,73,73,73,73,73,73,73,72,72,72,72,71,71,71,71,71,71,71,71,71,70,70,69,69,69,69,68,67,66,66,66,66,65,65,64,63,62,62,61,61,60,60,60,60,61,62,62,63,64,65,66,67,68,70,71,72,72,72,72,72,72,73,73,73,73,73,73,73,74,74,75,75,74,74,74,73,73,73,74,73,73,73,73,73,74,74,74,74,74,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,73,73,74,74,74,73,73,73,73,73,73,73,73,73,73,72,72,72,72,73,73,72,72,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,73,73,72,72,71,70,70,70,69,69,68,68,67,67,66,67,67,68,69,70,71,72,73,73,74,74,73,73,73,74,75,75,74,73,73,74,76,78,75,67,52,32,15,5,8,22,41,59,69,73,72,71,70,71,72,72,73,73,73,73,73,73,73,73,73,72,72,72,72,72,72,72,72,72,72,71,71,71,70,70,70,70,70,70,70,69,69,69,69,68,68,68,68,67,67,66,65,65,64,64,64,63,62,61,60,60,60,60,60,61,61,62,62,63,64,65,65,66,67,68,69,70,71,71,71,71,71,71,72,72,73,73,73,72,72,73,73,73,73,73,73,73,73,73,73,73,73,73,72,72,72,72,72,72,72,71,71,71,71,71,71,71,72,72,72,72,72,72,72,72,72,71,71,71,72,72,73,73,72,72,72,72,72,73,73,73,73,73,72,72,72,72,72,73,73,73,73,73,72,72,72,73,73,74,73,73,73,73,73,73,73,73,73,73,73,73,72,72,72,72,71,71,71,70,70,70,70,69,69,68,67,67,68,69,71,72,73,73,73,73,73,73,73,73,74,75,75,75,74,74,74,75,77,77,75,67,52,34,18,10,12,26,45,62,71,74,73,72,72,72,73,74,74,74,75,75,74,74,74,74,74,74,74,74,74,73,73,73,73,74,74,73,73,73,73,73,73,73,72,72,71,71,71,71,71,70,70,70,69,69,69,68,68,68,68,67,66,65,64,63,63,62,62,62,63,63,63,63,64,65,66,67,69,69,70,71,72,72,73,73,74,74,74,74,75,75,76,76,74,72,70,70,69,69 ]; function drawBkg(canvasElem, squareSize, numSquaresPerBlock, minorLineWidthStr, majorLineWidthStr, lineColStr) { var nLinesDone = 0; var i, curX, curY; var ctx = canvasElem.getContext('2d'); ctx.clearRect(0,0,canvasElem.width,canvasElem.height); // draw the vertical lines curX=0; ctx.strokeStyle = lineColStr; while (curX < canvasElem.width) { if (nLinesDone % numSquaresPerBlock == 0) ctx.lineWidth = majorLineWidthStr; else ctx.lineWidth = minorLineWidthStr; ctx.beginPath(); ctx.moveTo(curX, 0); ctx.lineTo(curX, canvasElem.height); ctx.stroke(); curX += squareSize; nLinesDone++; } // draw the horizontal lines curY=0; nLinesDone = 0; while (curY < canvasElem.height) { if (nLinesDone % numSquaresPerBlock == 0) ctx.lineWidth = majorLineWidthStr; else ctx.lineWidth = minorLineWidthStr; ctx.beginPath(); ctx.moveTo(0, curY); ctx.lineTo(canvasElem.width, curY); ctx.stroke(); curY += squareSize; nLinesDone++; } } // position that will be treated as 0,0 when drawing our points. var originX=49; var originY=72; function drawSamples(nSamplesToDraw, firstSample, lineWidthStr, lineColourStr) { var can = byId('canvas'); var ctx = can.getContext('2d'); ctx.strokeStyle = lineColourStr; ctx.lineWidth = lineWidthStr; console.log(firstSample); ctx.beginPath(); ctx.moveTo( originX+firstSample-1, dataSamples[firstSample-1]+originY ); for (var i=0; i<nSamplesToDraw; i++) { var curSample = dataSamples[i + firstSample]; ctx.lineTo( originX+firstSample+i, curSample+originY ); } ctx.stroke(); } var curFrame=0; var nPointsPerFrame = 4; function drawCurFrame() { if ((dataSamples.length - (nPointsPerFrame * curFrame)) < nPointsPerFrame) // will we over-run the end of the array of datapoints? { curFrame = 0; // if so, reset drawBkg(byId('canvas'), 9.43, 5, "0.5", "1.5", "black"); } drawSamples(nPointsPerFrame, nPointsPerFrame*curFrame, "1", "blue"); curFrame++; requestAnimationFrame( drawCurFrame ); } </script> <style> #canvas { border: solid 1px black; background-color: #FFFFFF; } </style> </head> <body> <div id='txt'></div> <canvas id="canvas" width="1350" height="1300"></canvas> </body> </html>
Update Now that I see you have provided some more info I get what you want. The problem is you need to draw a fixed number of line segments within time t. As you do not know how long each frame could take you can not rely on a fixed frame rate. The alternative it to just use the current time and save the end time. Get the start time and then each frame draw all the should be drawn until the current time. As the line segments being drawn will not be displayed until the next screen refresh the time you get will be approx 16ms behind so will need to adjust for that. What I have done is keep track of the average frame time and used half that time to estimate when the new canvas update will be displayed. Its a bit pedantic but might as well show how to get a required time as close as possible. If you dont care its a few ms out then just remove the average frame time stuff. You will be at most 30ms off on a slow machine. var canvas; // canvas var ctx; function getCanvas () { // to do // get canvas and context } function drawGrid () { // to do // draw the grid } function drawTimedLine(){ if(canvas === undefined){ // if the canvas not available get it getCanvas(); } // clear the canvas is repeating animation ctx.clearRect(0, 0, canvas.width, canvas.height); drawGrid(); var array_1 = ; // your data // All stuff needed for timed animation. // The frame you render will not be displayed untill the next // vertical refresh which is unknown, Assume it is one frame. var startDelay = 1000; // if Needed time in milliseconds to delay start var endTime; // hold the time that the animation has to end var lastDataPoint; // holds the last point drawn to var timeToDraw = 5 * 1000; // how long the animation should last var repeatAfter = 1 *1000; // if you want to repeat the animatoin var frameCount = 0; // count the frames to get average frame time var startTime; //the start time; var numberPoints = array_1.length; // number of points; var startX = 49; // line starts at var yOffset = 72; // line Y offset var endX = 512; // line ends at. var width = endX - startX; // width var xStep = width / numberPoints; // X step per point var pointsPerMS = numberPoints / timeToDraw; // get how many points per ms should be drawn // function to draw function drawWave() { // variable needed var averageframeTime, timeLeft, i, currentTime; currentTime = new Date().valueOf(); // gets the time in millisecond; if (startTime === undefined) { // Is this the first frame startTime = currentTime; // save the start time; endTime = currentTime + timeToDraw; // workout when the end time is; lastDataPoint = 0; // set the data position to the start; averageframeTime = 0; // no frames counted so frame time is zero } else { frameCount += 1; // count the frames // get the average frame time averageframeTime = (currentTime - startTime) / frameCount; } // get the time this frame // will most likely be displayed // then calculate how long // till the end timeLeft = endTime - Math.min(endTime, currentTime + averageframeTime / 2); // now get where we should // be when the frame is presented pointPos = Math.floor(pointsPerMS * (timeToDraw - timeLeft)); // now draw the points from where we last left of // till the new pos; ctx.lineWidth = 4; ctx.strokeStyle = 'blue'; ctx.beginPath(); ctx.moveTo( // move to first point lastDataPoint * xStep + startX, array_1[lastDataPoint] + yOffset ); // draw each line from the last drawn to the new position for (i = lastDataPoint + 1; i <= pointPos && i < numberPoints; i++) { // Add the line segment ctx.lineTo( i * xStep + startX, array_1[i] + yOffset ); } ctx.stroke(); // execute the render commands lastDataPoint = pointPos; // update the last point if (pointPos < numberPoints) { // are we there yet??? requestAnimationFrame(drawWave); // no so request another frame }else{ // if you want to repeat the animation setTimeout(drawTimedLine , repeatAfter ); } } // start the line animation with delay if needed setTimeout(drawWave,startDelay); } // use this if you want it to start as soon as page is ready. document.addEventListener("DOMContentLoaded",drawTimedLine); // or use if you want it to start when page has images loaded and is ready // document.addEventListener("load",drawTimedLine); I have also added the ability to repeat the animation. If not needed just remove that code My original answer Dont know what the problem is with speed as it runs quite well on my machine. To set up a better start use function startFunction(){ // your code } document.addEventListener("DOMContentLoaded",startFunction); This will wait until the page has loaded and parsed the page. Images and other media may not have loaded but the page is ready to be manipulated. Not sure what you mean with 5 seconds. Assuming you may want the thing to sart in 5 seconds. The following will do that. document.addEventListener("DOMContentLoaded",function() {setTimeout(startFunction,5000);}); I would ask why plot the graph one entry at a time with requestAnimationFrame 1250 is not that many lines to draw. If you add ctx.beginPath() ctx.moveTo(/*first point*/) then loop all points with ctx.moveTo(/*points*/) then ctx.stroke() will run realtime on but the slowest of devices. BTW ctx.lineWidth is a Number not a string. Also you have two context? Use the one context for the canvas. Remove ctxt and just use ctx and finally you don't need to add type='text/javascript' to the script tag as Javascript is the default.
1) It cannot take that long to draw 1000 lines, even 100000 lines won't take more than 10 ms on any decent Browser. Look else where the time is lost. 2) The core issue of your code is that it lacks modularity. Split your code into a few clear functions, group the parameters into a few objects only, name and indent things properly. Below an (incomplete but working) example of how this might look. var cv, ctx; var data = null; var debug = true; // --------------------------------------- // define here all graphic related parameters var gfxParams = { canvasWidth: 600, canvasHeight: 600, gridColor: '#A66', gridSpacing: 10, gridLineWidth: 0.5, gridStrongLinesEvery: 5, lineColor: '#AEB', lastLineColor: '#8A9' // , ... }; // define here all animation related parameters var animationParams = { duration: 5, startTime: -1 } // --------------------------------------- // main // --------------------------------------- window.onload = function() { data = getData(); setupCanvas(data); launchAnimation(); } // --------------------------------------- // function setupCanvas(data) { cv = document.getElementById('cv'); cv.width = gfxParams.canvasWidth; cv.height = gfxParams.canvasHeight; ctx = cv.getContext('2d'); // here you should translate and scale the context // so that it shows your data. } function drawGrid(ctx) { var i = 0, pos = 0, lw = gfxParams.gridLineWidth; ctx.fillStyle = gfxParams.gridColor; var vLineCount = gfxParams.canvasWidth / gfxParams.gridSpacing; for (i = 0; i < vLineCount; i++) { pos = i * gfxParams.gridSpacing; ctx.fillRect(pos, 0, lw, gfxParams.canvasHeight); } var hLineCount = gfxParams.canvasHeight / gfxParams.gridSpacing; for (i = 0; i < hLineCount; i++) { pos = i * gfxParams.gridSpacing; ctx.fillRect(0, pos, gfxParams.canvasWidth, lw); } } function animate() { requestAnimationFrame(animate); var now = Date.now(); // erase screen ctx.clearRect(0, 0, gfxParams.canvasWidth, gfxParams.canvasHeight); // draw grid drawGrid(ctx); // draw lines var lastIndex = getLastDrawnIndex(data, now - animationParams.startTime); drawLines(ctx, data, lastIndex); if (debug) { ctx.save(); ctx.fillStyle = '#000'; ctx.fillText(lastIndex + ' lines drawn. Time elapsed : ' + (now - animationParams.startTime), 10, 10); ctx.restore(); } } // comment function launchAnimation() { requestAnimationFrame(animate); animationParams.startTime = Date.now(); } // comment function getData() { var newData = []; for (var i = 0; i < 500; i++) { newData.push([Math.random() * 600, Math.random() * 600]); } return newData; } // comment function getLastDrawnIndex(data, timeElapsed_ms) { var timeElapsed = timeElapsed_ms / 1000; if (timeElapsed >= animationParams.duration) return data.length - 1; return Math.floor(data.length * timeElapsed / animationParams.duration); } function drawLines(ctx, data, lastIndex) { ctx.strokeStyle = gfxParams.lineColor; // other ctx setup here. for (var i = 0; i < lastIndex - 1; i++) { drawLine(ctx, data[i], data[i + 1]); } ctx.strokeStyle = gfxParams.lastLineColor; drawLine(ctx, data[lastIndex - 1], data[lastIndex]); } function drawLine(ctx, p1, p2) { ctx.beginPath(); ctx.moveTo(p1[0], p1[1]); ctx.lineTo(p2[0], p2[1]); ctx.stroke(); } <canvas id='cv'></canvas>
Error - Using Javascript and HTML canvases to make a mouse event drawing function [closed]
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers. This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers. Closed 8 years ago. Improve this question I am new to HTML canvases, but I have verified all my code and functions, or thought I had, and yet there is still no output on my website. It's supposed to be like the khanacademy draw function, where the user can select html <input>s to change colors, widths, shapes, etc., and then move their mouse around the screen to draw that shape with that color... I have no idea what is wrong, although when I 'inspect element' in Google Chrome, it says Uncaught SyntaxError: Unexpected identifier - games/drawing_shapes/js/draw_shapes.js:99. Line 99 is the very bottom one (mouse event function) and I'm guessing it means the $. I'm sorry this is so much code, but I'll try to organize it as best I can: // VARIABLES // //shapes var shape = "circle"; var shape_x; var shape_y; var shape_width = 10; var shape_height = 10; var circle_radius; var mouse_x; var mouse_y; var style = 'stroke'; //colors var colors = ["#FF0000", "#FF6600", "#FFFF00", "#00FF00", "#0066FF", "#CC0099", "#663300", "#000000"]; //red orange yellow green blue purple brown black //I haven't added the html to give the user the option to edit colors and so forth, so I just use the color below, but I will use the above colors as options once I get the script figured out... var color = "#FF0000"; var background_color = "#FFFFFF"; //canvas var canvas; var canvas_width; var canvas_height; var canvas_min_x; var canvas_max_x; var canvas_min_y; var canvas_max_y; //context var ctx; //initialize var initialized = false; // FUNCTIONS // function setShapeTo(newShape) { if (newShape == 'square' || 'circle') { shape = newShape; } else { shape = 'circle'; } } function drawCircle(x, y, r) { ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2, true); ctx.closePath(); if (style = 'fill') { ctx.fill(); } else { ctx.stroke(); } } function drawSquare(x, y, w, h) { ctx.beginPath(); ctx.rect(x, y, w, h); ctx.closePath(); if (style = 'fill') { ctx.fill(); } else { ctx.stroke(); } } function reset() { ctx.clearRect(0, 0, canvas_width, canvas_height); drawRectangle(0, 0, canvas_width, canvas_height); } function drawStage() { ctx.fillStyle = color; ctx.strokeStyle = color; circle_radius = shape_width / 2; /*shape_height = shape_width;*/ if (shape == 'square') { drawSquare(shape_x, shape_y, shape_width, shape_height); } else { drawCircle(shape_x, shape_y, circle_radius); } } function initialize() { canvas = document.getElementById('draw_shapes_canvas'); ctx = canvas.getContext('2d'); canvas_width = $("#draw_shapes_canvas").width(); canvas_height = $("#draw_shapes_canvas").height(); canvas_min_x = $("#draw_shapes_canvas").offset().left; canvas_max_x = canvas_min_x + canvas_width; canvas_min_y = $("#draw_shapes_canvas").offset().top; canvas_max_y = canvas_min_y + canvas_height; initialized = true; /*interval_id = setInterval(drawStage(), 10);*/ } function onMouseMove(event) { if (event.pageX > canvas_min_x && event.pageX < canvas_max_x && event.pageY > canvas_min_y && event.pageY < canvas_max_y && initialized == true) { shape_x = Math.max(event.pageX - canvas_min_x - (shape_width / 2), 0); shape_x = Math.min(canvas_width - shape_width, shape_x); shape_y = Math.max(event.pageY - canvas_min_y - (shape_height / 2), 0); shape_y = Math.min(canvas_height - shape_height, shape_y); } } $(document).ready(function() { initialize(); } $(document).mousemove(onMouseMove); Here is the html code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>MySite.com | Draw Shapes</title> <link type="text/css" rel='stylesheet' href='css/draw_shapes-style.css' media="screen"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> </head> <body> <script type="text/javascript" src="js/draw_shapes.js"></script> <canvas id="draw_shapes_canvas" width="500" height="400">Your browser does not support this game structure.</canvas> </body> </html> Maybe I need to put the script in the <head> tag, or after the <canvas>? I don't think that's it, though. Thanxxxxxxx a ton in advance for whoever contributes to this post and hopefully it is organized well and that i didn't make a silly mistake.
Just missing a paren to close the ready call. $(document).ready(function() { initialize(); }); $(document).mousemove(onMouseMove); Or you could move the mousemove setting inside the function. Either way, you need to close it and adding the semicolon is a good idea. In response to your comment - I think you are also missing a call to connect your mousemove to a drawing routine. Just for fun, I added drawCircle(shape_x,shape_y,Math.random()*10); in to your onMouseMove conditional block. It did what I expected.
HTML5 canvas blinks while refreshing
I need to refresh an HTML5 canvas every two or three seconds. setInterval(writeCanvas, 2000); This canvas is filled with points and lines. Each abscissa and ordinate is stored in an XML file. So before updating the canvas I do an async request to the file on the server. The problem is that the canvas blinks. I guess it disappears while the async request is running. How could I get around this issue? Here is the code of writeCanvas: function drawLines(ctx, back, front, width, xArray, yArray) { ctx.strokeStyle = back; ctx.fillStyle = front; ctx.lineWidth = width; ctx.beginPath(); ctx.moveTo(xArray[0], yArray[0]); for (var i=1; i<xArray.length; i++) { ctx.lineTo(xArray[i],yArray[i]); } ctx.fill(); ctx.stroke(); ctx.closePath(); } function drawPoint(ctx, back, front, x, y, radius, startAngle, endAngle) { ctx.strokeStyle = back; ctx.fillStyle = front; ctx.beginPath(); ctx.arc(x,y,radius,startAngle,endAngle,endAngle); ctx.fill(); ctx.stroke(); ctx.closePath(); } function writeLabel(ctx, color, font, x, y, text) { ctx.fillStyle = color; ctx.font = font; ctx.beginPath(); if(x < 0) { x = 0; } ctx.fillText(text, x, y); ctx.fill(); ctx.closePath(); } function writeCanvas() { var elem = document.getElementById('profileCanvas'); if (!elem || !elem.getContext) { return; } var ctx = elem.getContext('2d'); if (!ctx) { return; } // apply the final size to the canvas elem.setAttribute('width', canvasWidth); elem.setAttribute('height', canvasHeight); $.get('profileStatus.xml', function(xml) { if(xml) { var testPoints = new Array(); $(xml).find('TP').each(function() { var selected = $(this).find('SELECTED:first').text(); if(selected == "YES") { var name = $(this).find('MODULE_NAME:first').text(); var state = $(this).find('STATE:first').text(); var tp = new ProfileTp(name, state, selected); testPoints.push(tp); } }); $.get('profile.xml', function(data) { if(data) { profileWidth = parseFloat($(data).find('MAIN > PROFILE > DIM_W').first().text()); profileHeight = parseFloat($(data).find('MAIN > PROFILE > DIM_H').first().text()); var backgroundColor = '#ddd'; var color = '#323232'; ctx.translate(0,canvasHeight); var xArray = new Array(); var yArray = new Array(); $(data).find('PROFILE > POINT > X').each(function(){ var x=parseFloat($(this).text()); xArray.push(x); }); $(data).find('PROFILE > POINT > Y').each(function(){ var y=parseFloat($(this).text()); yArray.push(y); }); drawLines(ctx, backgroundColor, color, 2, xArray, yArray); var finalArray = new Array(); $(data).find('TESTPOINTS > TP').each(function() { var labelName = $(this).find('MODULE_NAME:first').text(); var tp = $.grep(testPoints, function(obj){ return obj.NAME == labelName; }); if(tp.length == 1) { $(this).find('IHM').each(function(){ tp[0].LABEL_X = parseFloat($(this).find('LABEL > X:first').text()); tp[0].LABEL_Y = parseFloat($(this).find('LABEL > Y:first').text()); tp[0].MARKER_X = parseFloat($(this).find('MARKER > X:first').text()); tp[0].MARKER_Y = parseFloat($(this).find('MARKER >Y:first').text()); }); finalArray.push(tp[0]); } }); for(var i=0; i<finalArray.length; i++) { writeLabel(ctx, color, fontSize+"px Arial",(finalArray[i].MARKER_X+finalArray[i].LABEL_X),(finalArray[i].MARKER_Y+finalArray[i].LABEL_Y), finalArray[i].NAME); drawPoint(ctx, backgroundColor, color, finalArray[i].MARKER_X, finalArray[i].MARKER_Y, 8, 0, 2*Math.PI); } } else { console.error('No XML test points returned'); } }); } }); } There are two XML files. One contains all the points, lines and labels. The second contains only the points and labels that have to be displayed.
Setting a canvas' dimensions clears it entirely, so the lines : elem.setAttribute('width', canvasWidth); elem.setAttribute('height', canvasHeight); are likely to make your canvas 'blink'. GET requests are asynchronous so the canvas is cleared way before points data are computed and drawn. To fix this, change the dimensions inside your requests callbacks, right before drawing.
Crogo already mention the probable cause in the answer, but as a work around you could do: if (elem.width !== canvasWidth || elem.height !== canvasHeight) { // apply the final size to the canvas elem.setAttribute('width', canvasWidth); elem.setAttribute('height', canvasHeight); } The canvas size is only set if the size change. You should also try to avoid using setInterval (what if client is on a slow/unstable connection that makes it take longer than 2 second to load data..). If the download is still in progress and setInterval triggers you will initiate another download while the first one is still downloading. You will also risk get "double drawings" to the canvas as these calls stack up in the event queue: Rather trigger an setTimeout from inside your writeCanvas(): function writeCanvas() { //... load and draw setTimeout(writeCanvas, 1500); //compensate for time } Of course, if the data MUST be loaded every two seconds this would be inaccurate (not that setInterval is.. they both give an estimate only).
Drawing in canvas becomes slower and slower when it draws more stuff during loop
I am trying to incrementally draw 3 lines which are 120 degrees from each other from a point using html5 canvas. The vertex of each lines will become another 3 new center point and spawns another 3 lines at each center and it repeats this.. My problem is, the incremental speed becomes slower and slower (or the drawing becomes slower) as more items are drawn. (maybe something happens in my code but I am not quite familiar how canvas exactly works...). You can copy the code and run it in your local browser to see what I means. Please see my code (it is very easy to understand) and tell me what causes this. <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <canvas id="canvas" ></canvas> <script> window.requestAnimFrame = (function(callback) { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; })(); var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); canvas.width= window.innerWidth; canvas.height= window.innerHeight; // some staring test values var centerPt={x:canvas.width/2,y:canvas.height/2}; var radius=100; var angle=0; // calculate the 3 endpoints at 120 degree separations var endPt000=anglePoint(centerPt,90); var endPt120=anglePoint(centerPt,210); var endPt240=anglePoint(centerPt,330); var length = 0; var maxLength = 100; var centreSet = new Array(); centreSet = getCentres(); var counter = 0; var end = centreSet.length; init(); function init() { start(centreSet[0].x, centreSet[0].y); } function start(myX, myY) { centerPt.x = myX; centerPt.y = myY; animate(centerPt, length); } function animate(centerPt,length) { // update // clear ctx.clearRect(0, 0, canvas.width, canvas.height); // draw stuff draw(centerPt,length); length = length + 1; // request new frame if(length < maxLength){ requestAnimFrame(function() { animate(centerPt,length); }); } else{ if(counter < end){ counter = counter + 1; centerPt.x = centreSet[counter].x; centerPt.y = centreSet[counter].y; endPt000=anglePoint(centerPt,90); endPt120=anglePoint(centerPt,210); endPt240=anglePoint(centerPt,330); length = 0; setTimeout(function(){animate(centerPt, length);},600); } } } // draw a red center dot // draw 3 blue endpoint dots // draw 3 lines from center going slider% of the way to the endpoints function draw(centerPt,sliderValue){ var pct=sliderValue; ctx.clearRect(0,0,canvas.width,canvas.height); line(centerPt,pointAtPercent(centerPt,endPt000,pct),"green"); line(centerPt,pointAtPercent(centerPt,endPt120,pct),"green"); line(centerPt,pointAtPercent(centerPt,endPt240,pct),"green"); } // calc XY at the specified angle off the centerpoint function anglePoint(centerPt,degrees){ var x=centerPt.x-radius*Math.cos( degrees*Math.PI/180 ); var y=centerPt.y-radius*Math.sin( degrees*Math.PI/180 ); return({x:x,y:y}); } // just draw a line from point1 to point2 function line(pt1,pt2,color){ // ctx.beginPath(); ctx.moveTo(pt1.x,pt1.y); ctx.lineTo(pt2.x,pt2.y); ctx.strokeStyle=color; ctx.lineWidth=2; ctx.stroke(); } // calc XY which is a specified percent distance from pt1 to pt2 function pointAtPercent(pt1,pt2,sliderValue) { // calculate XY at slider% towards pt2 var x = pt1.x + (pt2.x-pt1.x) * sliderValue/100; var y = pt1.y + (pt2.y-pt1.y) * sliderValue/100; return({x:x,y:y}); } //the following are used to get all the center points... function getCentres() { var x = window.innerWidth/2; var y = window.innerHeight/2; centreSet[0] = centerPt; var ref = 0; var end = 0; var b = true; var tempCenter = centerPt; for(var j = 0; j < 5; j++){ tempCenter = centreSet[ref]; end = end + 1; centreSet[end] = anglePoint(tempCenter,90); end = end + 1; centreSet[end] = anglePoint(tempCenter,210); end = end + 1; centreSet[end] = anglePoint(tempCenter,330); ref = ref+1; } return centreSet; } </script> </body> </html>
The problem is you are appending and appending the path. This means that each time you call stroke() the new line together with all the old lines are stroked. You won't see this clearly as the old lines are drawn on top in the same location. And as more and more lines are added the more time it takes to stroke them.. To prevent this you need to break the path. Do this with beginPath(). If you activate your out-commented line it should work fine: function line(pt1,pt2,color){ ctx.beginPath(); //<-- activate this ctx.moveTo(pt1.x,pt1.y); ctx.lineTo(pt2.x,pt2.y); ctx.strokeStyle=color; ctx.lineWidth=2; ctx.stroke(); }