Chapter 15

Graphics with Canvas

WHAT’S IN THIS CHAPTER?

  • Understanding the <canvas> element
  • Drawing simple 2D graphics
  • 3D drawing with WebGL

Arguably, HTML5’s most popular addition is the <canvas> element. This element designates an area of the page where graphics can be created, on the fly, using JavaScript. Originally proposed by Apple for use with its Dashboard widgets, <canvas> quickly was added into HTML5 and found a very fast adoption rate amongst browsers. Internet Explorer 9+, Firefox 1.5+, Safari 2+, Opera 9+, Chrome, Safari for iOS, and WebKit for Android all support <canvas> to some degree.

Similar to the other parts of the browser environment, <canvas> is made up of a few API sets and not all browsers support all API sets. There is a 2D context with basic drawing capabilities and a proposed 3D context called WebGL. The latest versions of the supporting browsers now support the 2D context and the text API; support for WebGL is slowly evolving, but since WebGL is still experimental, full support will likely take longer. Firefox 4+ and Chrome support early versions of the WebGL specification, though older operating systems such as Windows XP lack the necessary graphics drivers for enabling WebGL even when these browsers are present.

BASIC USAGE

The <canvas> element requires at least its width and height attributes to be set in order to indicate the size of the drawing to be created. Any content appearing between the opening and closing tags is fallback data that is displayed ...

Get Professional: JavaScript® for Web Developers, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.