Html5 Canvas Introduction

1 minute read

Introduction

HTML5 Canvas is a drawing technology that runs on all modern web browsers. It can be used for drawing shapes, photo manipulation, real-time video processing, data visualization, building games and animations.

HTML5 Canvas allows you to draw anything you want directly in the web browser without the use of plugins like Flash or Java.

Canvas Element

HTML5 Canvas API is a 2D drawing API. The browser gives you a rectangular area on the html page and you can draw into this area using the canvas API. You can draw lines, shapes, images, text.

The Canvas API provides an interface for drawing graphics via JavaScript and the HTML <canvas> element.

The <canvas> element has only two attributes that are width and height. If width and height attributes are not set, the canvas width will be 300 pixels wide and the height 150 pixels.

Falback Content

The <canvas> element supports fallback content, in order to be displayed in older browsers that does not support it. Versions of Internet Explorer earlier than version 9 or textual browsers does not support the <canvas> element. Fallback content should be set to be displayed by those browsers.

Fallback content added by inserting the a content inside the <canvas> element. Browsers that does not support the <canvas> element will render only the fallback content inside it. Browsers that support <canvas> will render the canvas element instead of the fallback content.

Here is an example of HTML code that creates Canvas element in the HTML page:

<canvas id="canvas" width="300" height="300">
Your browser does not support HTML5 Canvas.
</canvas>

Canvas Example

You can draw on the canvas using JavaScript:

Code

<html> 
<body> 
<canvas width="300" height="300" id="canvas"></canvas> 
<script> 
var canvas = document.getElementById('canvas'); 
var context = canvas.getContext('2d'); 
context.fillStyle = "red"; 
context.fillRect(50, 50, 200, 200); 
</script> 
</body> 
</html> 

Result

References

  1. https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API
  2. https://en.wikipedia.org/wiki/Canvas_element
  3. https://joshondesign.com/p/books/canvasdeepdive/title.html
  4. https://www.w3.org/TR/2009/WD-html5-20090825/the-canvas-element.html
  5. http://bucephalus.org/text/CanvasHandbook/CanvasHandbook.html

Updated: