Many students end up using Canvas for later projects. This exercise explores how Canvas works at a basic level. It will give you an introduction to using canvas to draw shapes on a page.
Take a look at the index.html
that has been provided for you. Notice
that there is a canvas
element that has been included in the body.
This is the element that we will be working with. By default, the canvas
element has a width of 300px and a height of 150px.
In the practice.js
file, we have added an event listener that waits
for the document to be loaded before looking for the canvas element.
Create a 2D rendering context:
- Grab the
canvas
element by id and save it to a variable - Set the
height
andwidth
attributes of the canvas to500
- Call
getContext
on the canvas with'2d'
as an argument and save the return value asctx
- You will be setting attributes and calling methods on
ctx
for the rest of this exercise
- Pick a color (e.g.
'red'
,rgb(255,255,255)
, etc. ) to set as thefillStyle
attribute forctx
- Call
fillRect
with the appropriate dimensions to draw the rectangle on the canvas - Check that everything's working by executing
open index.html
in your terminal
To draw the circle:
- Invoke
beginPath
with no arguments - Invoke
arc
with the appropriate dimensions to draw a circle - Pick a color to set as
strokeStyle
- Set the
lineWidth
attribute to some integer - Invoke
stroke
with no arguments - Open
index.html
in your browser to view it
To fill in the circle:
- Pick a color to set as
fillStyle
- Invoke
fill
with no arguments - Open
index.html
in your browser to view it
See here for inspiration. Also review these examples of how to animate your drawings.