HTML Canvas 填充和描边
Canvas 填充和描边
要为 canvas 中的形状/对象定义填充颜色和轮廓颜色,我们使用以下属性:
属性 | 描述 |
---|---|
fillStyle |
定义对象/形状的填充颜色 |
strokeStyle |
定义对象/形状轮廓的颜色 |
fillStyle 属性
fillStyle
属性定义对象的填充颜色。
fillStyle
属性的值可以是颜色(颜色名称、RGB、HEX、HSL)、渐变或图案。
示例
将填充颜色设置为“绿色”,并使用 fillRect()
方法绘制一个填充的矩形。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(10,10, 100,100);
</script>
自己动手试一试 »
strokeStyle 属性
strokeStyle
属性定义轮廓的颜色。
strokeStyle
属性的值可以是颜色(颜色名称、RGB、HEX、HSL)、渐变或图案。
示例
将轮廓颜色设置为“蓝色”,并使用 strokeRect()
方法绘制一个带轮廓的矩形。
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.strokeStyle = "blue";
ctx.lineWidth = 5;
ctx.strokeRect(10,10, 100,100);
</script>
自己动手试一试 »
组合 fillStyle 和 strokeStyle
组合上面的两个矩形是完全合法的。
示例
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 填充的矩形
ctx.fillStyle = "green";
ctx.fillRect(10,10, 100,100);
// 轮廓矩形
ctx.strokeStyle = "blue";
ctx.lineWidth = 5;
ctx.strokeRect(10,10, 100,100);
</script>
自己动手试一试 »
带 Alpha 通道的 fillStyle 和 strokeStyle
你也可以为 fillStyle
和 strokeStyle
属性添加 Alpha 通道,以创建不透明度。
示例
将 fillStyle
和 strokeStyle
属性的不透明度设置为 50%
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 填充的矩形
ctx.fillStyle = "rgb(0 255 0 / 50%)";
ctx.fillRect(10,10, 100,100);
// 轮廓矩形
ctx.strokeStyle = "rgb(0 0 255 / 50%)";
ctx.lineWidth = 5;
ctx.strokeRect(10,10, 100,100);
</script>
自己动手试一试 »