Chapter 4. A Blank Canvas

"It's so fine and yet so terrible to stand in front of a blank canvas."

—Paul Cezanne

In this chapter we are heading out in a whole new direction. We will learn how to use the new HTML5 canvas element and API by creating a simple drawing application. Our application will use the canvas basics such as strokes, paths, lines, and shapes. We will create a toolbar using custom data attributes, which we learned in the previous chapter, to bind menu items to actions in our code.

We will learn the following in this chapter:

  • The canvas element and its drawing API
  • How to get a canvas context and what are its global properties
  • How to draw lines, rectangles, and other shapes
  • How to get the position of the mouse inside a canvas element
  • How to create a toolbar that contains drop-down menus
  • How to use custom data attributes to bind toolbar actions to JavaScript code

HTML5 canvas

Probably one of the most exciting new features of HTML5 is the canvas. You can use it to create drawings anywhere on a web page. The only way to do this previously was by using some other technology such as Flash, SVG, or some other browser plugin.

The HTML5 canvas is both an element and an API. The <canvas> element defines a rectangular area of a web page where graphics can be drawn. The canvas API works with a <canvas> element to provide the JavaScript interface to draw on the canvas. It is a low-level set of functions for drawing lines, rectangle, circles, and other graphic primitives.

The <canvas> element itself is very simple. You must set the width and height attributes to specify its size. You can optionally put content inside the <canvas> element to be displayed for browsers that don't support it. The good news is that the HTML5 <canvas> element is widely supported by nearly every modern browser. The following code creates a canvas element 600 pixels wide and 400 pixels high:

<canvas width="600" height="400">
  Sorry, your browser doesn't support canvas.
</canvas>

Note

If you set the width and height of a <canvas> element in CSS to something other than the size specified on the element, it will stretch or shrink the drawing in the canvas to fit, which may compromise on the image quality.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.89.85