- Created on Thursday, 24 February 2011 11:19
- Last Updated on Saturday, 14 December 2013 11:40
- Written by Terrence
- Hits: 3591
The canvas element is a container element much like the script element. It's a blank slate we can draw on. We define a canvas with a width and height like this:
Learning aboutÂ 2D context
The canvasâ€™s 2D context is a grid, with the top-left corner as the default origin. When you create a shape, you specify the starting X and Y coordinates and the width and height.
Accessing the 2d rendering context
- TheÂ fillStyleÂ Property fill the color
- The fillRect property will draws a rectangle thatâ€™s filled in a colour by default is Black
Notice here weâ€™re using the jQuery function again to ensure that the event fires when the document is ready. Weâ€™ r e looking for an element on the page with the ID of my_canvas, so weâ€™d better make sure we add our canvas element to the document so it can be found, and our detection will work.
Each shape is added onto its own layer, so you could create three boxesÂ with a 10-pixel offset, like this:
Adding text to the canvas involves choosing a font, a font size, and an alignment, and then applying the text to the appropriate coordinates on the grid. We can add the text'Sendesignz' to our canvas like this:
We draw lines on the canvas by playing a game of 'connect-the-dots.' We specify a starting point on the canvas grid and then specify additional points on the grid to move to. As we move around the canvas, the dots get connected
Drawing a Rectangle
Drawing a Box
lineWidth - change the width of a stroked outline
beginPath - starts a new path
moveTo - moves the point that the path is drown from
lineTo - drows a straight path to this point from the point defined in moveTo, or the point from the last call to lineTo.
When we're all done moving around the canvas, we have to call the stroke method to draw the line and then call the closePath method to stop drawing.
Using Fill Method Â to create a illusion
context.translate(x, y) is to add the translation transformation to the transformation matrix. The x and y arguments represent the translation distance in the horizontal direction and in the vertical direction. The arguments are in coordinate space units
Adding Solid Color
In the previous Examples, you saw briefly how to set the stroke and fill color for the drawing tools. We could set the color using the property fillStyle and storkStyle.
Adding Gradiant Color
We can create gradients and assign those to strokes and fills like this:
We just create a gradient object and set the color stops of the gradient. In this example, we're just going between two shades of red, but we could do a rainbow if we wanted.
Note that we have to set the color of things before we draw them.
Now we have a better understanding of how we can draw simple shapes on the canvas.