HTML and CSS Reference
In-Depth Information
As previously mentioned, we will be implementing a number of basic elements within
the canvas. In order to do this we must irst link the JavaScript ile to our webpage.
This ile will be responsible for the initialization, loading, and drawing of objects to
the canvas. In order for our scripts to have any effect on our canvas we must create a
separate ile called canvas example . Create this new ile within your text editor and
then insert the following code declarations:
var canvas = document.getElementById("canvas"), context = canvas.
These declarations are responsible for retrieving both the canvas element and
context. Using the canvas context, we can begin to draw primitives, text, and load
textures into our canvas. We will begin by drawing a rectangle in the top-left corner of
our canvas. In order to do this place the following code below our previous JavaScript
If you were to now view the original webpage we created, you would see the rectangle
being drawn in the top-left corner at position X: 15 , Y: 15 . Now that we have a
rectangle, we can look at how we would go about drawing a circle onto our canvas.
This can be achieved by means of the following code:
context.arc(350,150,40,0,2 * Math.PI);
How it works...
The irst code extract represents the basic framework required to produce a blank webpage
and is necessary for a browser to read and display the webpage in question. With a basic
webpage created, we then declare a new HTML5 canvas. This is done by assigning an id
attribute, which we use to refer to the canvas within our scripts. The canvas declaration then
takes a width and height attribute, both of which are also necessary to specify the size of the
canvas, that is, the number of pixels wide and pixels high.
Before any objects can be drawn to the canvas, we irst need to get the canvas element. This
is done through means of the getElementById method that you can see in our canvas
example. When retrieving the canvas element, we are also required to specify the canvas
context by calling a built-in HTML5 method known as getContext . This object gives access
to many different properties and methods for drawing edges, circles, rectangles, external
images, and so on.
Search WWH ::

Custom Search