Next page | Contents page |

Redrawing all shapes

Some readers will know that other kinds of loop are possible. I am using the basic for loop to be sure that the shapes are drawn in the right order, background first.

Now suppose DATA.shapes contains all of the shapes needed to draw the canvas, background rectangle first. Then we can redraw the canvas at any time by writing a function draw() that draws every element of the array of shapes. Call it whenever anything moves or changes.


	function draw()
	{
	  let g2 = DATA.g2;// (just shorter)
	  for (let i = 0; i < DATA.shapes.length; i++)
	  {
		let si = DATA.shapes[i];// First will be the background
		switch (si.kind)
		{
	      case "rect":
	        g2.fillStyle = si.fill;
	        g2.fillRect(si.x, si.y, si.w, si.h);
	        g2.strokeStyle = si.stroke;
	        g2.strokeRect(si.x, si.y, si.w, si.h);
	        break;
	      case "path":
	        let p = si.path;
	        g2.beginPath();
	        g2.moveTo(p[0].x, p[0].y);
	        for (let j = 1; j < p.length; j++)
	        {
	          g2.lineTo(p[j].x, p[j].y);
	        }
	        if (si.fill.length > 0)// not empty string
	        {
	          g2.closePath();
	          g2.fillStyle = si.fill;
	          g2.fill();
	        }
	        g2.strokeStyle = si.stroke;
	        g2.stroke();
	        break;
	      // any other cases...
	    }
	  }
	}
Next page | Contents page |