Colouring An Object

If we draw an object on a canvas element using JavaScript then we can allow our visitor to interact with the parts of that object to change its appearance. One way we might want them to be able to do this is to allow them to colour sections of the drawing by clicking on them. To perform this we are going to create four functions. The getMousePos() function will return the mouse position within the canvas, the inside() method will work out whether the mouse position is within the area we want to interact with and if so then which of the sections of that area it is in, the draw() function will actually draw or redraw the object our visitors can interact with, and the update() function will run whenever our visitor interacts with the canvas.

For the purpose of illustrating how to do this we are going to draw a ball on the canvas consisting of three separate areas. Initially all of the areas will be white but we'll change whichever area is clicked on to a previously selected colour. The available colours are displayed across the top of the canvas and the first colour is initially selected. Determining which colour is clicked is trivial since any click where the Y co-ordinate is less than the height of the colour bar is within that area and as all of the colours are displayed in the same order as in the array all we need to do is divide by the width of the colourareas and round down to get the position in the array of the corresponding colour. Determini9ng which partof the interactive area the mouse was in when clicked is slightly more difficult which is why we need to recreate the paths and then use isPointInPath() to work out if the mouse position is inside of the interactive area and if so what part of that area it is in.

To draw the ball we'll define a circular clipping region and then draw two offset circles within the clipping region, finishing off by drawing another circle around the clipping region. Both the inside() and draw() functions need to create the same paths within the canvas. The only difference is that the inside() function uses those paths to work out where the mouse was clicked while the draw() function actually draws toe elements. If the area you want your visitors to interact with is something other than the simple ball that I have used here then simply rewrite these two functions so that the draw function draws whatever you want it to draw and the inside function creates those paths and works out which part of your area the mouse is in when clicked.

After determining which region the mouse is in we can then redraw substituting the new colour in the appropriate area.

Here is the JavaScript code that allows the above canvas to function. You are most welcome to adapt this code to draw whatever you like on your canvas for your visitors to colour.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate