在javassript中使用drawimage类中的未捕获类型错误
尝试在javascript中使用图像作为属性创建类时出现问题。我用context.drawImage注释的那一行会引发这个错误。在javassript中使用drawimage类中的未捕获类型错误
未捕获的类型错误:未能执行上“CanvasRenderingContext2D”“的drawImage”:所提供的值不是类型的“(CSSImageValue或HTMLImageElement或SVGImageElement或HTMLVideoElement或HTMLCanvasElement或ImageBitmap或OffscreenCanvas)”。
我觉得这很有趣,因为当我看着图像时,我在调试时作为参数传递,它告诉我它是一个HTMLImageElement。我来自静态类型的语言,我不明白为什么有一个类型错误,当传递的对象显然是错误所要求的类型。 `
var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d');
var edgeY = 600;
function Start()
{
var letter = new Letter(true, 10);
}
function Letter(_isSyllable, speed)
{
this.isSyllable = _isSyllable;
this.imgObject = new Image(80, 80);
this.posY = 10;
this.speed = speed;
this.ImageReady = false;
var source;
if (this.isSyllable)
{
source = "./Maganhangzok/image_part_" + (Math.floor(Math.random() * 14 + 1)) + ".jpg";
}
else
{
source = "./Massalhangzok/image_part_" + (Math.floor(Math.random() * 20 + 1)) + ".jpg";
}
this.imgObject.src = source;
this.imgObject.onLoad = new function()
{
this.ImageReady = true;
console.log(this.imgObject);
context.drawImage(this.imgObject, 120, this.posY); //this one throws the exception
}
}
Letter.prototype.Move = new function()
{
this.posY += this.speed;
context.clearRect(120, this.posY, 80, 80);
if (!this.ImageReady)
{
return false;
}
if (this.posY + 80 > edgeY)
{
return true;
}
else
{
context.drawImage(this.imgObject, 120, this.posY);
return false;
}
}
</script>`
回答:
您需要首先调用的onLoad和设置源URL。
this.imgObject.onLoad = new function() {
this.ImageReady = true;
console.log(this.imgObject);
context.drawImage(this.imgObject, 120, this.posY); //this one throws the exception
}
this.imgObject.src = source;
以上是 在javassript中使用drawimage类中的未捕获类型错误 的全部内容, 来源链接: utcz.com/qa/258055.html