JS绘制作为课堂的方法
几天前,我在JavaScript中启动了一个简单的项目,并发现了这个问题。每次我重新加载Google页面时,我都会得到一个空的画布。我已经尝试从课堂上取出drawimage()函数,并且有效。但是,如果我需要将该功能用作类方法怎么办? (也我已经尝试将画布作为抽奖方法的参数传递,但它行不通)
所以这是有效的,但我不需要
const canvas = document.getElementById('main_canvas')
const ctx = canvas.getContext('2d')
var img = new Image()
img.src = 'some source'
ctx.drawImage(img,10,10)
,这不起作用,但应该
const canvas = document.getElementById('main_canvas')
const ctx = canvas.getContext('2d')
class Person
{
constructor(name){
this.name = name
this.img = new Image()
this.img.src = 'some source'
}
draw(){
ctx.drawImage(this.img,10,10)
}
}
var peter = new Person('Peter Griffin')
peter.draw()
I started a simple project in javascript a few days ago and found this issue. Every time I reload my google-page i get an empty canvas. I have already tried to take out the drawImage() function out of class and it worked. But what if I need to use that function as a class method? (Also I've already tried passing the canvas as an argument of the draw method but it doesn't work)
So this is working but I don't need it
const canvas = document.getElementById('main_canvas')
const ctx = canvas.getContext('2d')
var img = new Image()
img.src = 'some source'
ctx.drawImage(img,10,10)
And this isn't working but supposed to
const canvas = document.getElementById('main_canvas')
const ctx = canvas.getContext('2d')
class Person
{
constructor(name){
this.name = name
this.img = new Image()
this.img.src = 'some source'
}
draw(){
ctx.drawImage(this.img,10,10)
}
}
var peter = new Person('Peter Griffin')
peter.draw()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
原因很简单。要绘制时,您的图像不会加载。
您必须等到将图像加载到画布中之前。
The reason is simple. Your image is not loaded when you want to draw it.
You have to wait until the image is loaded before drawing it in the canvas.