Javascript HTML5画布错误
我正试图在画布上写一个益智游戏,所以我需要给益智块的每个部分一个背景图像。 但始终存在错误Uncaught TypeError:无法读取未定义的属性'drawImage' 任何帮助都将不胜感激Javascript HTML5画布错误,javascript,canvas,Javascript,Canvas,我正试图在画布上写一个益智游戏,所以我需要给益智块的每个部分一个背景图像。 但始终存在错误Uncaught TypeError:无法读取未定义的属性'drawImage' 任何帮助都将不胜感激 (function(){ function Block(image, l, t, w, h){ this.image = image; this.left = l; this.top = t; this.width = w;
(function(){
function Block(image, l, t, w, h){
this.image = image;
this.left = l;
this.top = t;
this.width = w;
this.height = h;
}
Block.prototype.draw = function(context){
context.drawImage(this.image, this.left, this.top, this.width, this.height, this.left, this.top, this.width, this.height);
}
window.Block = Block;
})();
var el = document.getElementById("puzzle_area");
var ctx = el.getContext("2d");
var image = new Image();
image.src = "background0.jpg";
image.onload = init;
var width = 100;
var height = width;
function init(){
for(var i = 0; i < 16; i++){
var x = (i % 4) * width;
var y = parseInt(i / 4) * height;
var block = new Block(image, x, y, width, height);
block.draw(ctx);
}
}
draw函数需要一个上下文参数,当您从块函数/对象中调用它时,不会将该参数传递给它。添加一个上下文参数,并在调用this.draw时使用它。我还没有测试它,但下面是我将代码更改为的内容:
(function(){
function Block(context, image, l, t, w, h){
this.image = image;
this.left = l;
this.top = t;
this.width = w;
this.height = h;
this.context = context;
this.draw();
}
Block.prototype.draw = function(){
this.context.drawImage(this.image, -this.left, -this.top, this.width, this.height, this.left, this.top);
}
window.Block = Block;
})();
var el = document.getElementById("puzzle_area");
var ctx = el.getContext("2d");
var image = new Image();
image.src = "background0.jpg";
image.onload = init;
var block = null;
var width = 100;
var height = width;
function init(){
for(var i = 0; i < 9; i++){
var x = (i % 400) * width;
var y = parseInt(i / 400) * height;
block = new Block(ctx, image, x, y, width, height);
// block is drawn automatically, no need to draw it again
// block.draw();
}
}
我已经发现问题了!语法正常,但drawImage的参数列表错误。还是谢谢你!似乎参数列表顺序不是唯一的问题。原始错误肯定是由于缺少上下文参数造成的;