一、简介
lineCap能够让我们设置线条的端点样式,例如
1. butt
const ctx = canvas.getContext("2d");ctx.lineCap = "butt"; // 默认样式,也可以显式指定
2.round
const ctx = canvas.getContext("2d");//圆头ctx.lineCap = "round";
3.square
const ctx = canvas.getContext("2d");//方头ctx.lineCap = "square";
二、全部代码展示
<template><div class="canvasPage"><!-- 写一个canvas标签 --><canvas class="main" ref="main"></canvas></div>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";// 获取canvas元素
const main = ref<HTMLCanvasElement>();// 绘制canvas
const drawCanvas = () => {// 确保获取到了canvas元素if (!main.value) return console.error("无法获取Canvas元素");const canvas = main.value;// 设置canvas的宽高canvas.width = 200;canvas.height = 100;// 获取Canvas绘制2D环境const ctx = canvas.getContext("2d");if (!ctx) return console.error("无法获取CanvasRenderingContext2D");// 设置三条线的起始Y坐标,保持平行const startY = 20;const lineSpacing = 20;// 第一条线:butt样式ctx.lineWidth = 12;ctx.lineCap = "butt"; // 默认样式,也可以显式指定ctx.beginPath(); // 开始新的路径ctx.moveTo(10, startY);ctx.lineTo(190, startY);ctx.stroke(); // 绘制线条// 第二条线:round样式ctx.lineCap = "round";ctx.beginPath(); // 开始新的路径ctx.moveTo(10, startY + lineSpacing);ctx.lineTo(190, startY + lineSpacing);ctx.stroke(); // 绘制线条// 第三条线:square样式ctx.lineCap = "square";ctx.beginPath(); // 开始新的路径ctx.moveTo(10, startY + lineSpacing * 2);ctx.lineTo(190, startY + lineSpacing * 2);ctx.stroke(); // 绘制线条
};
// 页面挂载后才能绘制
onMounted(() => {drawCanvas();
});
</script>
<style lang="scss" scoped>
.canvasPage {width: 100%;height: 100vh;display: flex;justify-content: center;align-items: center;background-color: #ffffff;.main {width: 200px;height: 100px;}
}
</style>