Using Canvas From JavaScript

CanvasThe other day we looked at setting up the canvas tag. But while the HTML element this set up a drawing surface, the actual drawing is handled from JavaScript. Here's how to get started.

Grabbing the Element and Retrieving the Context

Let's start with the code example we used last time:
<canvas id="myCanvas" width="200" height="200">
    Your browser does not support the canvas element.

You'll see that we set an id on the element so we can access it from JavaScript. Once we do that, we need to retrieve the graphics context
var canvasTag = document.getElementById("Canvas");
var context = canvasTag.getContext("2d");

You'll see that we retrieve the context by calling getContext() and passing it "2d". Currently, a 2d drawing context is all that browsers support. There was the thought that one day there might be a 3d drawing context, but for now it looks like 3d will be handled with WebGL technology.
Of course, we can actually create the canvas tag by using createElement(). But if we did-how would we detect if canvas was supported similar to how we did it via HTML?. By using feature detection, we check for the existence of the getContext method. See below.
var canvasTag = document.createElement("canvas");
if (canvasTag.getContext)
    var context = canvasTag.getContext("2d");

No comments :