为什么我的画布游戏代码从Java构造函数中的模块返回“未定义”?

问题描述

这是我从sprite.js导出的构造函数模块

export const Sprite = function(filename,sx,sy,sWidth,sHeight,dx,dy,dWidth,dHeight,x){


this.img = new Image()
this.img.src = `./img/${filename}`
this.sx = sx
this.sy = sy
this.sWidth = sWidth
this.sHeight = sHeight
this.dx = dx
this.dy = dy
this.dWidth = dWidth
this.dHeight = dHeight


this.draw = function(x){
    return x.drawImage(this.img,this.sx,this.sy,this.sWidth,this.sHeight,this.dx,this.dy,this.dWidth,this.dHeight)
}

}

与game.js相比,我是这样的:

  const ctx = game.getContext("2d");
  const player = new Sprite('player.png',10,ctx)


  console.log(player.draw(ctx)) // undefined

谢谢您的帮助!

解决方法

因为CanvasRenderingContext2D.drawImage()不返回值。

您究竟希望记录什么? drawImage()将提供的图像绘制到画布上。该功能的唯一输出是修改画布-您可以通过视觉检查来确认它是否起作用。

,

我忘了在gameloop中调用新的玩家构造函数。谢谢您的评论。

   import {Sprite} from "./modules/sprite.mjs"
   const ctx = game.getContext("2d");

   const player = new Sprite('player.png',64,65)

   function draw(){
          player.draw(ctx)
   }


   function gameloop(){
          draw()
          requestAnimationFrame(gameloop)
    }
    gameloop()