0

My Code is like this

    <html>
  <head>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200" style="display:none;"></canvas>
    <img id="canvasImg" onclick="myFunction()" alt="Right click to save me!">
    <script>
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        function myFunction() {
            var c = document.getElementsByTagName("canvas");
            // save canvas image as data url (png format by default)
            var dataURL = c.toDataURL();
            // set canvasImg image src to dataURL
            // so it can be saved as an image
            document.getElementById('canvasImg').src = dataURL;
        }
    </script>
  </body>
</html> 

When i click on canvasImg its throwing an error

Uncaught TypeError: Object #<NodeList> has no method 'toDataURL' 

I have made a fiddle here Can any one point out whats going wrong?

2 Answers 2

5

DEMO

document.getElementsByTagName returns array of elements objects, and no array objects have method toDataUrl

instead of this

var c = document.getElementsByTagName("canvas"); 

use

 var c = document.getElementsByTagName("canvas")[0];
Sign up to request clarification or add additional context in comments.

Comments

2
    function myFunction() {
         var canvas = document.getElementById("myCanvas");
         var context = canvas.getContext("2d");
         var img = document.getElementById("canvasImg");
         context.drawImage(img, 0, 0);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.