0

我的代码是这样的

    <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> 

当我点击canvasImg它抛出一个错误

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

我在这里做了一个小提琴 谁能指出出了什么问题?

4

2 回答 2

5

演示

document.getElementsByTagName 返回元素对象数组,并且没有数组对象有方法 toDataUrl

而不是这个

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

采用

 var c = document.getElementsByTagName("canvas")[0];
于 2013-11-01T07:33:50.860 回答
2
    function myFunction() {
         var canvas = document.getElementById("myCanvas");
         var context = canvas.getContext("2d");
         var img = document.getElementById("canvasImg");
         context.drawImage(img, 0, 0);
    }
于 2013-11-01T07:39:58.677 回答