node.js - node.js 上的 jsdom + canvas : toDataURL() error

标签 node.js canvas jsdom

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

相关文章:

events - Node.js 事件处理顺序

Javascript Canvas : base64 back to file after resizing&resampling?

javascript - 在 Canvas 上画一个漂亮的激光(星球大战)

javascript - React + enzyme 单元测试,无法访问 window.addEventListener

jquery - node.js - 如何使用 jsdom/node-jquery 更新我的页面的外观?

javascript - Node.js jsdom/express 响应缓存?

javascript - 尝试删除 Node.js Express MongoDB Jade 应用程序中的条目

javascript - 如何让本地 eslint 插件与本地安装的 eslint 一起工作

javascript - npm 'module not found' ,但一切似乎都设置正确

javascript - Canvas javascript游戏中的碰撞