Create 2d context *without* canvas

It is possible to use a canvas without displaying it on the page. You could do the following:

// Create a canvas element
var canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 400;

// Get the drawing context
var ctx = canvas.getContext('2d');

// Then you can do stuff, e.g.:
ctx.fillStyle = '#f00';
ctx.fillRect(20,10,80,50);

Once you've used the canvas, you can of course add it to the document

var element = document.getElementById('canvas_container');
element.appendChild(canvas);

Or you could make an image from it:

var new_image_url = canvas.toDataURL();
var img = document.createElement('img');
img.src = new_image_url;

Or you could access the canvas data as values with:

var image_data = ctx.getImageData(0, 0, canvas.width, canvas.height);
var rgba_byte_array = image_data.data;
rgba_byte_array[0];  // red value for first pixel (top left) in the canvas

Interestingly enough, if you create a canvas object and store its context in a variable, that variable has its own pointer to the canvas object. Since you can't use getContext("2d") without a canvas, you might as well only have one canvas pointer. If you're like me and hate having a two references to the same object, you could do this:

Original:

var canvas=document.createElement("canvas");
var context=canvas.getContext("2d");

alert(Boolean(context.canvas==canvas));// true.

What I'm talking about:

var context=document.createElement("canvas").getContext("2d");

alert(context.canvas);// The canvas object.

Now you can do all of your important canvas stuff through the context variable. After all, context is accessed more often than the canvas variable. When you do need it just reference it through the context:

context.canvas.width=320;
context.canvas.height=320;
document.body.appendChild(context.canvas);

And if you don't want to bother with the canvas just leave the variable alone, it's not like you wanted to use it anyway.


How about: OffscreenCanvas()?

And the answer is probably no, since this is only supported in Firefox 44.0+ currently.

var offscreen = new OffscreenCanvas(256, 256);

https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas

https://html.spec.whatwg.org/multipage/scripting.html#the-offscreencanvas-interface

(Added for reference here, as this may well be new to the spec since this question was asked more than 6 years ago! And hopefully will be more widely adopted)