`canvas.getContext(' 2d')`返回`Object`而不是`CanvasRenderingContext2D`

时间:2016-03-20 23:53:42

标签: javascript html5-canvas jasmine phantomjs karma-jasmine

将2.1.1与Karma和Jasmine一起使用,我得到一个TypeError代码:

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.drawImage(...) // TypeError here for Phantom

Chrome 47和Firefox 43返回的context类型为CanvasRenderingContext2D

Link to GitHub issue

1 个答案:

答案 0 :(得分:0)

我认为问题在于您在网页上下文之外运行该代码。

以下代码段应该可以使用

var webPage = require('webpage');
var page = webPage.create();

page.onConsoleMessage = function(msg) {
    console.log('The web page said: ' + msg);
};

page.open('http://phantomjs.org/', function(status) {
    page.evaluateJavaScript(function() {
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        console.log(canvas);
        console.log(context);
        console.log(typeof context.drawImage);
    });
    phantom.exit();
});

在PhantomJS中运行此脚本时的输出是;

The web page said: [object HTMLCanvasElement]
The web page said: [object CanvasRenderingContext2D]
The web page said: function