使用canvas@1.2.3& jsdom@3.1.2与节点v0.12.2,我在尝试使用canvas toDataURL()
函数时遇到错误。
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);
});
HTML测试:
<!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>
jsdom测试:
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中的HTML测试中,我获得了正确的base64编码的画布数据,而在node.js中,错误显示为:
TypeError: Cannot read property 'toDataURL' of undefined
答案 0 :(得分:0)
您正在按ID进行选择,因此没有数组。删除[0]它应该可以工作,或者用数组选择另一种方式:
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());