Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize html canvas element?

I have a canvas element defined statically in the html with a width and height. If I attempt to use JavaScript to resize it dynamically (setting a new width and height - either on the attributes of the canvas or via the style properties) I get the following error in Firefox:

uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame :: file:///home/russh/Desktop/test.html :: onclick :: line 1" data: no]

Is it possible to resize this element or do I have to destroy it and create a new element on the fly?

like image 645
russx2 Avatar asked Dec 01 '08 14:12

russx2


People also ask

How do you scale a canvas in HTML?

You can scale your canvas with content by "bouncing" the content off a temporary canvas while you resize the original canvas. This save+redraw process is necessary because canvas content is automatically cleared when you resize the canvas width or height. So .


2 Answers

You didn't publish your code, and I suspect you do something wrong. it is possible to change the size by assigning width and height attributes using numbers:

canvasNode.width  = 200; // in pixels canvasNode.height = 100; // in pixels 

At least it works for me. Make sure you don't assign strings (e.g., "2cm", "3in", or "2.5px"), and don't mess with styles.

Actually this is a publicly available knowledge — you can read all about it in the HTML canvas spec — it is very small and unusually informative. This is the whole DOM interface:

interface HTMLCanvasElement : HTMLElement {            attribute unsigned long width;            attribute unsigned long height;    DOMString toDataURL();   DOMString toDataURL(in DOMString type, [Variadic] in any args);    DOMObject getContext(in DOMString contextId); }; 

As you can see it defines 2 attributes width and height, and both of them are unsigned long.

like image 122
Eugene Lazutkin Avatar answered Sep 25 '22 09:09

Eugene Lazutkin


Note that if your canvas is statically declared you should use the width and height attributes, not the style, eg. this will work:

<canvas id="c" height="100" width="100" style="border:1px"></canvas> <script>     document.getElementById('c').width = 200; </script> 

But this will not work:

<canvas id="c" style="width: 100px; height: 100px; border:1px"></canvas> <script>     document.getElementById('c').width = 200; </script> 
like image 33
sam hocevar Avatar answered Sep 24 '22 09:09

sam hocevar