[英]How to draw over canvas with Javascript
我正在構建我的第一個迷你 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>
updateGameArea
調用myGameArea.clear()
然后嘗試調用不存在的update
。 運行時您沒有收到錯誤消息嗎?
您可能想要調用myGamePiece.update()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.