2013-11-01 80 views
0

我的代碼是這樣的HTML5畫布沒有方法「toDataURL」

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

我已經做了fiddle here 任何一個可以指出什麼出錯了?

回答

5

DEMO

document.getElementsByTagName返回的數組元素的對象,並且沒有陣列的對象具有方法toDataUrl

代替這種

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

使用

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