Next page | Contents page |

Freehand drawing

To draw a continuous line we need to relate a series of clicks to one object. So we need some more Javascript syntax.

Arrays are indexed by integers (whole numbers) in square brackets. The first element is at index 0. Unlike most other languages Javascript does not distinguish between integers and numbers with digits after a decimal point. Make sure array indexes are integers. Functions Math.round() or Math.floor() are useful for that.

We need a list to which we can add a new point every time we click the mouse. The simplest Javascript type for this is Array. We will start one in the run() function like this:


	DATA.path = [];

That creates an array that does not yet have anything in it. One of the useful methods of Array is push() for pushing something into the end of the array. When have got a new mouse point we can add it to the array like this:


	DATA.path.push(point);

Then to draw a line we get the points out in the same order by using [i], where i is a whole number going from 0 (the first element) to DATA.path.length - 1 (the last element). A useful property of any array is length and that is maintained automatically by the system.


	g2.beginPath();
	g2.moveTo(DATA.path[0].x, DATA.path[0].y);//first point
	for (let i = 1; i < DATA.path.length; i++)//the rest
	{
	  g2.lineTo(DATA.path[i].x, DATA.path[i].y);
	}
	g2.stroke();

A new feature here is the for loop. Read all about it on MDN.

i++ means increase i by 1 (each time round the loop).

Next page | Contents page |