I’m new to javascript and am having an error. I’m sure I am skipping some basic concept… sorry.
here is the problem.
I use on my html this code:
<div>
<script type='text/javascript'>
var myCanvas = document.getElementsByTagName("canvas");
document.write('<img src="'+myCanvas[0].toDataURL("image/png")+'"/>');
</script></div>
I have only one canvas on my document. The error I see in chrome is:
Uncaught TypeError: Cannot read property '0' of undefined sankey.html:128 (anonymous function)
If I enter
document.write('<img src="'+myCanvas[0].toDataURL("image/png")+'"/>');
(the exact same line) in the java script chrome console, it works! How is this possible?
You forgot the
[0]:getElementsByTagNamereturns a array of elements, you’ll have to select one out of it. (Even if the array only contains 1 element)A “cleaner” way to do this would be to set a id (
id="myCanvas") on the canvas, and usegetElementById, but since you’re only using 1 canvas,getElementsByTagNamewill work.The reason it was returning
undefinedis probably that your code was executed before the canvas was loaded.Wrap your code in a function, then register the function to the “load” event