HTML 5 Notes For Professional Chapter 32

Chapter 32: Canvas

AttributeDescription
heightSpecifies the canvas height
widthSpecifies the canvas width

Basic Example

The canvas element was introduced in HTML5 for drawing graphics.


 Cannot display graphic. Canvas is not supported by your browser (IE<9)

The above will create a transparent HTML element of 300×150 px in size.

You can use the canvas element to draw amazing stuff like shapes, graphs, manipulate images, create engaging
games etc. with JavaScript.

The canvas’s 2D drawable layer surface Object is referred to as CanvasRenderingContext2D; or from a
HTMLCanvasElement using the .getContext (“2d”) method:

var ctx = document.getElementById("myCanvas").getContext("2d");
// now we can refer to the canvas's 2D layer context using `ctx`
ctx.fillStyle = "#f00";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); // x, y, width, height
ctx.fillStyle = "#000";
ctx.fillText("My red canvas with some black text", 24, 32); // text, x, y

jsFiddle example

Drawing two rectangles on a


 
 Draw two rectangles on the canvas
   Your browser does not support canvas.
251454

Pin It on Pinterest

Share This