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?
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 .
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.
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> 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With