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 画布形状


Canvas 形状

要在画布上绘制由直线组成的不同形状,我们使用以下方法

方法 描述 绘制
beginPath() 声明我们将要绘制一个新的路径(不绘制)
moveTo(x,y) 设置画布上形状的起点(不绘制)
lineTo(x,y) 设置画布上形状的子点或终点(不绘制)
stroke() 绘制线条(从起点,穿过子点到终点)。默认描边颜色为黑色

示例

抱歉,您的浏览器不支持画布。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();

// 设置起点
ctx.moveTo(20,20);

// 设置子点
ctx.lineTo(100,20);
ctx.lineTo(175,100);
ctx.lineTo(20,100);

// 设置终点
ctx.lineTo(20,20);

// 描边(进行绘制)
ctx.stroke();
</script>
自己尝试 »


更多示例

示例

抱歉,您的浏览器不支持画布。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.moveTo(100,20);
ctx.lineTo(180,100);
ctx.lineTo(20,100);
ctx.lineTo(100,20);
ctx.stroke();
</script>
自己尝试 »

strokeStyle 属性

The strokeStyle 属性定义描边的颜色。

它必须在调用 stroke() 方法之前设置。

示例

抱歉,您的浏览器不支持画布。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();

// 定义一个矩形
ctx.moveTo(20,20);
ctx.lineTo(180,20);
ctx.lineTo(180,100);
ctx.lineTo(20,100);
ctx.lineTo(20,20);

// 定义一个三角形
ctx.moveTo(100,20);
ctx.lineTo(180,100);
ctx.lineTo(20,100);
ctx.lineTo(100,20);

ctx.strokeStyle = "red";
ctx.stroke();
</script>
自己尝试 »

×

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.