我想使用原型绘制许多不同大小的圆圈,并在其上绘制相同的图像。问题是,圆圈不会出现在它们上面绘制的图像。
圆圈仍然存在,因为它们在使用笔划时可见,但不会绘制图像。我能够在没有原型的情况下绘制带有图像的弧线,但是一旦我使用它,它就无法工作。
控制台中没有出现错误,因此我不清楚我缺少什么。我已经尝试将事件监听器移到原型之外,但圆形图像仍然没有出现。
如果任何人有任何见解,或许可以解决为什么这不起作用,他们可以分享,这将非常感激。
这是代码:
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>
在这里,我只是改变了两件事,以使您的代码工作。
load
)。onload
this
您的代码中有两个问题。首先,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)
这是一种替代方式,您可以加载更模块化的图像,如果您正在制作游戏,this.xPos
类将派上用场。
this.yPos
totalLoadedthis.radius
totalLoadedconst 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