In this lesson I created a drawing application that draws brush strokes according to user input. The brush transitions in size and colour as the user moves around.
First I get the <canvas> and its context in 2d space 'ctx'. I assign initial values for: 'strokeStyle', 'lineJoin', 'lineCap', 'lineWidth' and 'globalCompositeOperation'. These help define the look of the brush stroke. Then I initialise variables that will determine if the user 'isDrawing', their 'lastX' and 'lastY' positions, the current 'hue', and 'direction' to determine if the brush is supposed to increase or decrease in size.
I listen on the <canvas> element for 'mousedown', mousemove', 'mouseup' and 'mouseout' events.
On 'mousedown' - Pass the event into a function(e), set 'isDrawing' to true and set the 'lastX' and 'lastY' values to match the current values from the event 'e.offsetX' and 'e.offsetY'.
On 'mousemove' - Pass the event into a function Draw(e). If 'IsDrawing' is not true, exit the function. Otherwise, inject the 'hue' into the context 'strokeStyle' using template strings.
Then begin a path in the context (.beginPath()). Start the path at 'lastX' and 'lastY' (.moveTo()). Draw a line to the current 'e.offsetX' and 'e.offsetY' (.lineTo()). Then fill out the line stroke (.stroke()).
Next increment the 'hue' value, if it's >= 360, reset it to 0 to loop back around on the colour wheel. Increase or decrease the 'lineWidth' in a range between two set values, If the 'lineWidth' hits the bounds, flip the polarity of 'direction' and increment 'lineWidth' in the opposite direction.
'mouseup' or 'mouseout' - Set 'isDrawing' to false.
See the Pen
JavaScript30 - 8 - Fun With HTML5 Canvas by Corey Noble (@CoreyNoble)
on CodePen.