Now that we’ve discussed everything that has to do with lines and stroking, it’s time for shapes and their filling.
Rectangle
To quickly create a rectangle, use
rect(x, y, width, height)
ctx.beginPath(); ctx.rect(20,20,100,100); ctx.stroke();
Quick Rectangles
Because rectangles are so important, there are three methods that simplify the process of creating, stroking and filling a rectangle.
To create a filled rectangle (using the current fill settings), use
fillRect(x, y, width, height)
To create a stroked rectangle (using the current stroke settings), use
strokeRect(x, y, width, height)
To erase part of the canvas – setting all pixels to transparent black – use
clearRect(x, y, width, height)
ctx.beginPath(); ctx.strokeStyle="green"; ctx.strokeRect(20,20,100,100);
Circles
To create a circle, or semi-circle, one can simply use the arc
method. If you create a semi-circle, don’t forget to close off the path once you’re done.
ctx.beginPath(); ctx.fillStyle="green"; ctx.arc(50,50,30,0,2*Math.PI); ctx.fill(); ctx.beginPath(); ctx.fillStyle="red"; ctx.arc(100,100,30,0,Math.PI); ctx.closePath(); ctx.fill();
Custom Shapes
We can create any custom shape we want simply by using a series of straight/curved lines, and then closing the path. There’s no magic involved here!
ctx.beginPath(); ctx.fillStyle="green"; ctx.moveTo(20,20); ctx.lineTo(60,20); ctx.lineTo(80,50); ctx.lineTo(60,80); ctx.lineTo(20,80); ctx.lineTo(0,50); ctx.closePath(); ctx.fill();