jsdom + canvas上node.js:toDataURL()错误

使用canvas@1.2.3&jsdom@3.1.2与节点v0.12.2,我试图使用canvastoDataURL()函数时出现错误。

canvasTest.js:

 $(function(){ var canvas = $('<canvas></canvas>').attr({'id':'canvasTest', 'width':'500', 'height':'500'}); var ctx=canvas[0].getContext("2d"); ctx.beginPath(); ctx.arc(100,75,50,0,2*Math.PI); ctx.stroke(); $('#canvasWrap').append(canvas); }); 

HTMLtesting:

 <!doctype html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="canvasTest.js"></script> <script type="text/javascript"> $(function(){ console.log($('body').html()); console.log($('#canvasTest').length); console.log($('#canvasTest')[0].toDataURL()); }) </script> </head> <body> <div id="canvasWrap"></div> </body> </html> 

jsdomtesting:

 var canvas = require('canvas'); var jsdom = require('jsdom'); jsdom.env({ html: '<html><body><div id="canvasWrap"></div></body></html>', scripts: ['127.0.0.1/jquery-2.1.4.min.js','127.0.0.1/canvasTest.js'], done:function (err,win) { var $ = win.jQuery; $(function(){ console.log($('body').html()); console.log($('#canvasTest').length); console.log($('#canvasTest')[0].toDataURL()); }); } }); 

在Chrome中的HTMLtesting中,我得到了正确的base64编码的canvas数据,而在node.js中,错误如下:

 TypeError: Cannot read property 'toDataURL' of undefined 

你正在selectID,所以没有数组。 删除[0],它应该工作,或另一种方式select一个数组:

 console.log($('canvas')[0].toDataURL()); 

或者试试这个:

 console.log($('#canvasTest').toDataURL()); 

或这个:

 console.log(win.$("#canvasTest").toDataURL()); 

或这个:

 console.log(win.document.getElementById("canvasTest").toDataURL()); 

或这个:

 console.log(win.document.getElementsByTagName("canvas")[0].toDataURL());