简体   繁体   English

Canvas 项目未正确渲染 function

[英]Canvas project not properly rendering function

I cannot seem to get my Rect to render in real time no matter how much I try.无论我尝试多少,我似乎都无法让我的 Rect 实时渲染。 The player.update() method only seems to work when it's not nested in the animate function, cause when I put the player.update method in function animate() it straight up doesn't run player.update() 方法似乎只在它没有嵌套在动画 function 中时才起作用,因为当我将 player.update 方法放在 function animate() 中时,它不会直接运行

const canvas = document.querySelector('canvas')

const c = canvas.getContext('2d')

canvas.width = innerWidth
canvas.height = innerHeight

const gravity = 0.5
class Player{
    constructor() {
        this.position = {
            x: 100,
            y: 100
        }
        this.velocity = {
            x: 0,
            y: 0
        }
        this.width = 30
        this.height = 30
    }

    drawPlayer() {
        c.fillStyle = 'red'
        c.fillRect(
            this.position.x, 
            this.position.y, 
            this.width, 
            this.height
            )
    }
    update() {
        this.position.y += this.velocity.y
        this.drawPlayer()

        if (this.position.y + this.height + this.velocity.y <= canvas.height)
            this.velocity.y += gravity
        else this.velocity.y = 0
    }
}

const player = new Player()

function animate() {
    requestAnimationFrame(animate)
    console.log('go')
    c.clearRect(0, 0, canvas.width, canvas.height)
    player.update()
}

Call animate调用animate

Sorry it's a boring answer, but it just simple looks like you're never actually starting your "game loop" of animate() .抱歉,这是一个无聊的答案,但看起来您从未真正开始animate()的“游戏循环”。 Seems fine otherwise.别的好像还好。

Small concern.小担心。 I would do the requestAnimationFrame last, otherwise it's just going to make a loop of calling itself over and over again.我会最后做requestAnimationFrame ,否则它只会一遍又一遍地循环调用自己。 Chrome handled it well, but I'm not confident in other browsers (excluding firefox). Chrome 处理得很好,但我对其他浏览器(不包括 firefox)没有信心。

 const canvas = document.querySelector('canvas') const c = canvas.getContext('2d') canvas.width = innerWidth canvas.height = innerHeight const gravity = 0.5 class Player { constructor() { this.position = { x: 100, y: 100 } this.velocity = { x: 0, y: 0 } this.width = 30 this.height = 30 } drawPlayer() { c.fillStyle = 'red' c.fillRect( this.position.x, this.position.y, this.width, this.height ) } update() { this.position.y += this.velocity.y this.drawPlayer() if (this.position.y + this.height + this.velocity.y <= canvas.height) this.velocity.y += gravity else this.velocity.y = 0 } } const player = new Player() function animate() { //console.log('go') c.clearRect(0, 0, canvas.width, canvas.height) player.update() requestAnimationFrame(animate) } animate();
 <canvas></canvas>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM