Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an HTML canvas without a DOM element?

I'd like to have an HTML canvas context that I can paint to and read off-screen (in this example, writing text and reading the shape that is created, but it's a general question). I may also want to use a canvas as an off-screen frame-buffer.

I suppose I could create a hidden DOM element but I'd rather create it from JavaScript (I may want to create and destroy a number of canvas at runtime).

Possible?

like image 475
Joe Avatar asked Jul 07 '11 10:07

Joe


People also ask

Is canvas a DOM element?

The DOM Canvas Object is used to represent the HTML <Canvas> element. The <canvas> tag is used to draw a graphics in the document using javascript. It is new in HTML5. The canvas element is accessed by getElementById().

How do you make a canvas required in HTML?

A canvas element is required by your linked canvas demo, but you can alternatively use the drag/drop API built into html+JS. And you can "manually" move DOM objects using mouse events as described in Kaiido's answer. The canvas is required for your linked demo to work.


1 Answers

You can create a new canvas element with document.createElement:

var canvas = document.createElement('canvas'); 

and then get the context from it. Just make sure you set the width and height. You don't have to add the canvas to the tree in order to make it work:

DEMO

But you definitely have to create that node. You could create a function for that though:

function createContext(width, height) {     var canvas = document.createElement('canvas');     canvas.width = width;     canvas.height = height;     return canvas.getContext("2d"); } 

But that is where my competency ends... whether you can somehow transfer a context to another context or canvas, I don't know...

like image 108
Felix Kling Avatar answered Sep 20 '22 00:09

Felix Kling