9 Feb 2014

HTML5 Canvas


What is the the HTML5 canvas, and what can it do?

Below you will find some examples and links to summarise its capabilities.





Wikipedia: Canvas Element

The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images. It is a low level, procedural model that updates a bitmap and does not have a built-in scene graph.


Canvas consists of a drawable region defined in HTML code with height and width attributes. JavaScript code may access the area through a full set of drawing functions similar to those of other common 2D APIs, thus allowing for dynamically generated graphics. Some anticipated uses of canvas include building graphs, animations, games, and image composition.

Examples from www.w3schools.com

Draw a Rectangle

var ctx = document.getElementById("myCanvas1").getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(10, 10, 150, 75);

Draw a Line

var ctx = document.getElementById("myCanvas2").getContext("2d");
ctx.moveTo(10, 10);
ctx.lineTo(190, 90);

Draw a circle

var ctx = document.getElementById("myCanvas3").getContext("2d");
ctx.arc(95, 50, 40, 0, 2 * Math.PI);

Draw text

var ctx = document.getElementById("myCanvas4").getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World", 10, 50);
ctx.strokeText("Hello World", 10, 90);

Draw using gradiant

var ctx = document.getElementById("myCanvas5").getContext("2d");
// Create gradient
var grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);

Draw an Image

var ctx = document.getElementById("myCanvas6").getContext("2d");
var img = document.getElementById("cupimage");
ctx.drawImage(img, 10, 10);
jsfiddle-logo-white Jsfiddle
blog comments powered by Disqus

Image attribution: "cubos web" by Cristian Blanxer is licensed under CC BY 2.0

About Me

My first computer was a Commodore VIC-20, I had great fun trying to code text adventures and side scrolling shoot ‘em ups in BASIC. This helped me lead the way as the first in my school to pass a computer exam.

Currently I work as a Senior Software Engineer in Bedford for a FTSE 100 Company. Coding daily in C#, JavaScript and SQL. Outside of work I work on whatever is interesting me at that time.