为什么我的图像不会出现在画布上?

问题描述 投票:2回答:3

我想使用原型绘制许多不同大小的圆圈,并在其上绘制相同的图像。问题是,圆圈不会出现在它们上面绘制的图像。

圆圈仍然存在,因为它们在使用笔划时可见,但不会绘制图像。我能够在没有原型的情况下绘制带有图像的弧线,但是一旦我使用它,它就无法工作。

控制台中没有出现错误,因此我不清楚我缺少什么。我已经尝试将事件监听器移到原型之外,但圆形图像仍然没有出现。

如果任何人有任何见解,或许可以解决为什么这不起作用,他们可以分享,这将非常感激。

这是代码:

const ctx = document.getElementById('canvas').getContext('2d');
class Balls {
  constructor(xPos, yPos, radius){
    this.xPos = xPos;
    this.yPos = yPos;
    this.radius = radius;
  }
}
Balls.prototype.render  = function(){
  const img = document.createElement('img');
  img.src = 'crystal.jpg';
  ctx.arc(this.xPos, this.yPos, this.radius, 0, Math.PI*2)
  ctx.stroke();	
  ctx.clip();
  img.addEventListener('onload', function(e){
    ctx.drawImage(img, this.xPos - this.radius, this.yPos - this.radius, 
    this.radius*2, this.radius*2);
  });
};
let object = new Balls(100, 100, 50);
object.render();
<canvas id='canvas'></canvas>
javascript object html5-canvas prototype drawimage
3个回答
1
投票

在这里,我只是改变了两件事,以使您的代码工作。

  1. qazxsw poi用于事件监听器而不是qazxsw poi。
  2. 使用箭头函数以依赖父上下文而不是动态上下文(load)。

onload
this

1
投票

您的代码中有两个问题。首先,const ctx = document.getElementById('canvas').getContext('2d'); class Balls { constructor(xPos, yPos, radius) { this.xPos = xPos; this.yPos = yPos; this.radius = radius; } } Balls.prototype.render = function() { const img = document.createElement('img'); img.src = 'https://via.placeholder.com/150.png?text=vijay' ctx.arc(this.xPos, this.yPos, this.radius, 0, Math.PI * 2) ctx.stroke(); ctx.clip(); img.addEventListener('load', (e) => { ctx.drawImage(img, this.xPos - this.radius, this.yPos - this.radius, this.radius * 2, this.radius * 2); }); }; let object = new Balls(100, 100, 50); object.render();事件应该是<canvas id='canvas'></canvas>。其次,onload在事件监听器函数中是未知的,所以load等都是未定义的并且this不起作用。

我在qazxsw poi,qazxsw poi,qazxsw poi中使用了一些变量,可以在事件监听器回调函数中使用。希望这可以帮助!

this.radius
ctx.drawImage(img, this.xPos - this.radius, this.yPos - this.radius, 
    this.radius*2, this.radius*2)

1
投票

这是一种替代方式,您可以加载更模块化的图像,如果您正在制作游戏,this.xPos类将派上用场。

this.yPostotalLoadedthis.radiustotalLoadedconst ctx = document.getElementById('canvas').getContext('2d'); class Balls { constructor(xPos, yPos, radius) { this.xPos = xPos; this.yPos = yPos; this.radius = radius; } } Balls.prototype.render = function() { const img = new Image(); img.src = 'https://source.unsplash.com/random'; var xPos = this.xPos, yPos = this.yPos, radius = this.radius ctx.arc(xPos, yPos, radius, 0, Math.PI * 2) ctx.stroke(); ctx.clip(); img.addEventListener('load', function(e) { console.log("load") ctx.drawImage(img, xPos - radius, yPos - radius, radius*2, radius*2); }); }; let object = new Balls(100, 100, 50); object.render();totalImages<canvas id='canvas'></canvas>

Img

Off-topic -
if you want to load multiple images then you can add a
© www.soinside.com 2019 - 2024. All rights reserved.