JS绘制作为课堂的方法

发布于 2025-02-12 01:04:39 字数 720 浏览 3 评论 0原文

几天前,我在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

把梦留给海 2025-02-19 01:04:40

原因很简单。要绘制时,您的图像不会加载。

您必须等到将图像加载到画布中之前。

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 = 'monimage.jpg'
    }
    on_image_loaded(f) {
        this.img.onload = f;
    }
    draw(){
        ctx.drawImage(this.img,10,10)
    }
}

var peter = new Person('Peter Griffin')
peter.on_image_loaded(function() {
    peter.draw();
});

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.

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 = 'monimage.jpg'
    }
    on_image_loaded(f) {
        this.img.onload = f;
    }
    draw(){
        ctx.drawImage(this.img,10,10)
    }
}

var peter = new Person('Peter Griffin')
peter.on_image_loaded(function() {
    peter.draw();
});

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文