0

Im new to javascript. I just want to generate some random points every frame and draw a graph using them. But the program doesnt clear the canvas before drawing. So the program just keeps adding new pixels. In the end i want to draw graphs acording to the value of currencies (EUR,USD...). Here is a picture with the graph generated ony once: https://ibb.co/fn1qXd Here is a picture when i generate the graph every frame: https://ibb.co/dmQCdJ

<script>

let canvas = document.getElementById("myCanvas");
let context = canvas.getContext("2d");

function loop()
{
    context.clearRect(0, 0, canvas.width, canvas.height);

    let growth=20;
    points[0]=0;
    for(i=1;i<points.length;i++)
        points[i]=points[i-1]+(Math.random()*growth-growth/2);          

    context.strokeStyle="#42BBDB";
    for(i=0;i<points.length-1;i++)
    {
        context.lineWidth=1;
        context.moveTo(i, points[i]+160);
        context.lineTo(i+1, points[i+1]+160);
    }                       

    context.stroke();

    requestAnimationFrame(loop);
}

for(i=0;i<values.length;i++)
    for(j=0;j<values.length;j++)
        if(i!=j)
        {
            let name=values[i]+" "+values[j];
            points=new Array(400);  
            points[0]=0;
            for(k=1;k<points.length;k++)
            {
                let growth=20;
                points[k]=points[k-1]+(Math.random()*growth-growth/2);
            }
        }
loop();
</script>
Robert
  • 3
  • 1

2 Answers2

0

You should add:

values = [1, 2, 3, 4, 5];
points = [];

Right before the for loop in order to work.

Working Example in Fiddle

let canvas = document.getElementById("myCanvas");
let context = canvas.getContext("2d");

function loop()
{
 context.clearRect(0, 0, canvas.width, canvas.height);
 
 let growth = 20;
 
 for (i = 1; i < points.length; i++)
 {
  points[i] = points[i - 1] + (Math.random() * growth - growth / 2);
 }
 
 context.strokeStyle = "#42BBDB";
 
 for (i = 0; i < points.length - 1; i++)
 {
  context.lineWidth = 1;
  context.moveTo(i, points[i] + 160);
  context.lineTo(i + 1, points[i + 1] + 160);
 }
 
 context.stroke();
 
 requestAnimationFrame(loop);
}

values = [1, 2, 3, 4, 5];
points = [];

for (i = 0; i < values.length; i++)
{
 for (j = 0; j < values.length; j++)
 {
  if (i != j)
  {
   let name = values[i] + " " + values[j];
   
   points = new Array(400);
   
   points[0] = 0;
   
   for (k = 1; k < points.length; k++)
   {
    let growth = 20;
    points[k] = points[k - 1] + (Math.random() * growth - growth / 2);
   }
  }
 }
}

loop();
<canvas id="myCanvas" width="200" height="100"></canvas>
Kostas
  • 140
  • 1
  • 13
0

You should call context.beginPath(); after context.clearRect(0, 0, canvas.width, canvas.height); as described in this answer: https://stackoverflow.com/a/16035567/3337236

https://jsfiddle.net/2wogtevL/

mihai1990
  • 632
  • 5
  • 20