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 画布线条


画布线条绘制

要在画布上绘制线条,我们使用以下方法

方法 描述 绘制
beginPath() 声明我们即将绘制一条新路径(不进行绘制)
moveTo(x,y) 设置画布上线条的起点(不进行绘制)
lineTo(x,y) 设置画布上线条的终点(不进行绘制)
stroke() 绘制线条。默认描边颜色为黑色

示例

抱歉,您的浏览器不支持画布。

在位置 (0,0) 定义一个起点,在位置 (200,100) 定义一个终点。然后使用 stroke() 实际绘制线条

<script>
// 创建一个画布
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// 定义一条新路径
ctx.beginPath();

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

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

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


lineWidth 属性

lineWidth 属性定义线条的宽度。

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

示例

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

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.stroke();
</script>
自己试试 »

strokeStyle 属性

strokeStyle 属性定义线条的颜色。

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

示例

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

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.strokeStyle = "red";
ctx.stroke();
</script>
自己试试 »

lineCap 属性

lineCap 属性定义线条的端点样式("butt"、"round" 或 "square")。

默认值为 "butt"。

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

示例

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

ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(175,75);
ctx.lineWidth = 10;
ctx.lineCap = "round";
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.