Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

游戏 Canvas


HTML 的 <canvas> 元素在网页上显示为一个矩形对象


HTML Canvas

<canvas> 元素非常适合在 HTML 中制作游戏。

<canvas> 元素提供了制作游戏所需的所有功能。

使用 JavaScript 在 <canvas> 上绘制、写入、插入图像等等。


.getContext("2d")

<canvas> 元素有一个内置对象,称为 getContext("2d") 对象,它具有用于绘制的方法和属性。

您可以在我们的 Canvas 教程 中了解更多关于 <canvas> 元素和 getContext("2d") 对象的信息。


开始

要制作游戏,首先创建一个游戏区域,并使其准备好绘制。

示例

function startGame() {
  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]);
  }
}
亲自尝试 »

对象 myGameArea 将在本教程的后面部分拥有更多属性和方法。

函数 startGame() 调用 myGameArea 对象的 start() 方法。

start() 方法创建一个 <canvas> 元素,并将其插入为 <body> 元素的第一个子节点。


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.