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
     ❯   

HTML 在画布上绘制


使用 JavaScript 在画布上绘制

画布上的绘制是通过 JavaScript 完成的。

画布最初是空白的。要显示任何内容,需要一个脚本访问渲染上下文并在其上绘制。

以下示例在画布上绘制一个红色的矩形,从位置 (0,0) 开始,宽度为 150,高度为 75

示例

<canvas id="myCanvas" width="200" height="100" style="border:1px solid black;">
</canvas>

<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 150, 75);
</script>
自己试一试 »

步骤 1:查找画布元素

首先,您必须找到 <canvas> 元素。

可以使用 HTML DOM 方法 getElementById() 访问 <canvas> 元素

const canvas = document.getElementById("myCanvas");

步骤 2:创建绘制对象

其次,您需要一个画布的绘制对象。

getContext() 方法返回一个包含绘制工具(属性和方法)的对象

const ctx = canvas.getContext("2d");

步骤 3:在画布上绘制

最后,您可以在画布上绘制。

使用 fillStyle 属性将填充颜色设置为红色

ctx.fillStyle = "red";

fillStyle 属性可以是颜色、渐变或图案。默认的 fillStyle 为黑色。

fillRect(x, y, width, height) 方法绘制矩形,用填充样式颜色填充,在画布上

ctx.fillRect(0, 0, 150, 75);

×

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.