在 Node v0.12.2 中使用 canvas@1.2.3 和 jsdom@3.1.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 编码 Canvas 数据,而在 node.js 中,错误如下:
TypeError: Cannot read property 'toDataURL' of undefined
最佳答案
你是按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());
关于node.js - node.js 上的 jsdom + canvas : toDataURL() error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31102597/