简体   繁体   English

如何使用 Javascript 在画布上绘制

[英]How to draw over canvas with Javascript

I'm working on building my first mini JS game and working through the w3schools tutorial but can't even get my first component to load in the codepen preview area.我正在构建我的第一个迷你 JS 游戏并完成 w3schools 教程,但甚至无法在 codepen 预览区域中加载我的第一个组件。 This has been a very disappointing first couple steps.这是非常令人失望的前几步。 I know myGameArea loads fine as it's styled to pop but I just want a simple red square to draw on top of it.我知道 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>

updateGameArea calls myGameArea.clear() and then tries to call update which doesn't exist. updateGameArea调用myGameArea.clear()然后尝试调用不存在的update Are you not getting an error when this runs?运行时您没有收到错误消息吗?

You probably want to call myGamePiece.update() .您可能想要调用myGamePiece.update()

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

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