带有内置图像对象的Canvas组件构造函数;t显示's图像

Canvas component constructor with the built-in image object doesn't show's the image

本文关键字:图像 显示 构造函数 组件 内置 对象 Canvas      更新时间:2023-09-26

我正在使用画布,并尝试创建一个构造函数"Component"来创建各种元素。这个想法是,它必须能够不仅用一些颜色填充创建的元素,而且用背景图像填充。它可以用颜色填充元素,但无法加载图像。控制台中没有错误。屏幕上什么都没有。需要帮助。现在整个代码是这样的:

var myRect;
function startGame (){
    workingArea.create();
    myRect = new Component(30, 30, "grass.jpg", 10, 120, 'image');
}
var workingArea = {
    canvas: document.createElement('canvas'),
    create: function (){
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext('2d');
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
    }
};

function Component(width, height, color, x, y, type){
    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;
    this.type = type;
    if (this.type === 'image'){
        this.image = new Image();
        this.image.src = color;
    }
    var ctx = workingArea.context;
    if (type === 'image'){
        this.image.onload = ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
    }
    else{
        ctx.fillStyle = color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
}
    }
    else{
        ctx.fillStyle = color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
}

查看如何加载图像,然后在画布上绘制:https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Example_A_simple_line_graph

如果感兴趣的话,这里有一个很好的解释来解释如何在回调中访问"this":如何在回调内访问正确的"this"上下文?

在你的情况下,它应该看起来像:

function Component(width, height, color, x, y, type){
  this.width = width;
  this.height = height;
  this.x = x;
  this.y = y;
  this.type = type;
  var ctx = workingArea.context;
  if (type === 'image') {
    this.image = new Image();
    // This is async, so you need to pass your drawImage inside a callback function
    this.image.onload = function() {
      ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
    }.bind(this); // Bind the "this" to the callback
    this.image.src = color; // This is valid, just unfortunate to name it color.
  } else {
    ctx.fillStyle = color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
}