简体   繁体   English

HTML5画布错误

[英]A HTML5 canvas ERROR

I'am trying to write a puzzle game in canvas,so i need to give each part of puzzle block a background image. 我正在尝试在画布上编写一个益智游戏,所以我需要给益智块的每个部分提供背景图像。 but always a error "Uncaught TypeError: Cannot read property 'drawImage' of undefined " 但总是出现错误“未捕获的TypeError:无法读取未定义的属性'drawImage'”

any help will be appreciated! 任何帮助将不胜感激!

(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);
    }
}

Your draw() function requires a context parameter which you're not passing to it when you're calling it from within your Block() function/object. 您的draw()函数需要一个上下文参数,当您从Block()函数/对象中调用它时,不会将其传递给它。 Add a context parameter to that and use it when calling "this.draw()". 为此添加一个上下文参数,并在调用“ this.draw()”时使用它。

I haven't tested it, but here is what I changed your code to: 我还没有测试过,但是这是我将您的代码更改为:

(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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM