views:

62

answers:

2

I am currently looking for a way to create a canvas 2d rendering context without actually having a canvas element on the page. I could dynamically create a canvas element and hide it, but then again I don't want to show the image directly to the user anytime, so there's no point of actually having a canvas element in the page. So I'm basicly looking for something that is similar to

var image = new Image( );

but only for canvas 2d rendering context (pseudo code)

var context = new 2dContext( );

Is there functionality like this? I wasn't able to find anything like it. Calling

var context = new CanvasRenderingContext2D( );

which is the name of the rendering context interface by HTML5 spec just gives me awkward errors in Firefox:

uncaught exception: [Exception... "Cannot convert WrappedNative to function" nsresult: "0x8057000d (NS_ERROR_XPC_CANT_CONVERT_WN_TO_FUN)" location: "JS frame :: http://localhost/ :: <TOP_LEVEL> :: line 25" data: no]
+2  A: 

Hi,

You may want to take a look at Raphaël.

I know this is not exactly what you're asking for, but it is a:

2d rendering context without actually having a canvas element on the page

Alin Purcaru
+1 because Raph is AWESOME
Matt Ball
Yea, but it has nothing to do with canvas contexts.
mbq
+2  A: 

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 byte_array = ctx.getImageData(0,0,canvas.width,canvas.height);
byte_array[0];  // red value for first pixel (top left) in the canvas
andrewmu
Thank you for the answer. I was aware of this method, but felt it's not exactly what I was looking for. Propably though this is my best bet.
Daniel Baulig