如何使用Javascript在画布上绘制

如何使用Javascript在画布上绘制,javascript,html,canvas,Javascript,Html,Canvas,我正在构建我的第一个迷你JS游戏,并完成w3schools教程,但我甚至无法在codepen预览区加载我的第一个组件。这是非常令人失望的最初几步。我知道myGameArea加载良好,因为它的风格流行,但我只想在它上面画一个简单的红方块 var myGamePiece; function startGame() { myGamePiece = new component(30, 30, "red", 10, 120); myGameArea.start(); } var myGameA

我正在构建我的第一个迷你JS游戏,并完成w3schools教程,但我甚至无法在codepen预览区加载我的第一个组件。这是非常令人失望的最初几步。我知道myGameArea加载良好,因为它的风格流行,但我只想在它上面画一个简单的红方块

var myGamePiece;

function startGame() {
  myGamePiece = new component(30, 30, "red", 10, 120);
  myGameArea.start();
}

var myGameArea = {
  canvas: document.createElement("canvas"),
  start: function() {
    this.canvas.width = 480;
    this.canvas.height = 270;
    this.context = this.canvas.getContext("2d");
    document.body.insertBefore(this.canvas, document.body.childNodes[0]);
    this.interval = setInterval(updateGameArea, 20);
  },
  clear: function(){
    this.context.clearRect(0,0, this.canvas.width, this.canvas.height);
  }
}


function component(width, height, color, x, y) {
    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;    
    this.update = function(){
        ctx = myGameArea.context;
        ctx.fillStyle = color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
}

function updateGameArea() {
  myGameArea.clear();
  myGameArea.update();
}

<button onClick="startGame()">
Press
</button>
var-myGamePiece;
函数startName(){
myGamePiece=新组件(30,30,“红色”,10,120);
myGameArea.start();
}
var myGameArea={
画布:document.createElement(“画布”),
开始:函数(){
this.canvas.width=480;
this.canvas.height=270;
this.context=this.canvas.getContext(“2d”);
document.body.insertBefore(this.canvas,document.body.childNodes[0]);
this.interval=setInterval(updateGameArea,20);
},
清除:函数(){
this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
}
}
功能组件(宽度、高度、颜色、x、y){
这个。宽度=宽度;
高度=高度;
这个.x=x;
这个。y=y;
this.update=函数(){
ctx=myGameArea.context;
ctx.fillStyle=颜色;
ctx.fillRect(this.x,this.y,this.width,this.height);
}
}
函数updateGameArea(){
myGameArea.clear();
myGameArea.update();
}
按

updategamerea
调用
myGameArea.clear()
,然后尝试调用不存在的
update
。运行此操作时是否没有收到错误


你可能想调用
myGamePiece.update()

控制台中有错误吗?你似乎没有定义
myGameArea.update()
你的意思是
myGamePiece.update()
?是的,花了一个小时和一半的时间梳理代码,没有看到那个小的打字错误。谢谢