createPattern(backgroundImg," repeat");返回null

时间:2015-03-19 13:01:57

标签: html5 canvas html5-canvas

var backgroundImg = new Image(50, 50);
backgroundImg.src = "img/grass.png";
var backgroundPattern = screen.createPattern(backgroundImg, "repeat");

backgroundPattern为null。为什么?

1 个答案:

答案 0 :(得分:1)

因为你需要给图像加载时间。为此,请在Image实例上使用onload处理程序。请注意,这是异步的,因此您需要考虑其余的代码:

var backgroundPattern;
var backgroundImg = new Image(50, 50);

backgroundImg.onload = function() {
    // provided screen holds the 2D context of the canvas:
    backgroundPattern = screen.createPattern(this, "repeat");    

    // execute next part of your code from here... 
    // next();
};

backgroundImg.src = "img/grass.png";