一、fillStyle概念
在canvas中我们可以用fillStyle定义接下来的图像的样式,默认为黑色#000。
我们可以使用纯色、渐变、和纹理(例如图片)进行填充,来达到自己想要的效果。
二、代码
<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 = 400; // 增加宽度以适应三个方块canvas.height = 100;// 获取Canvas绘制上下文const ctx = canvas.getContext("2d");if (!ctx) return console.error("无法获取CanvasRenderingContext2D");// 绘制纯色方块ctx.fillStyle = "red";ctx.fillRect(0, 0, 100, 100);// 绘制线性渐变方块// 创建线性渐变let gradientLinear = ctx.createLinearGradient(0, 0, 0, 100);//添加颜色断点gradientLinear.addColorStop(0, "rgba(67, 55, 135, 1)");gradientLinear.addColorStop(1, "rgba(176, 63, 191, 1)");//填充渐变ctx.fillStyle = gradientLinear;ctx.fillRect(100, 0, 100, 100);// 绘制径向渐变方块let gradientRadial = ctx.createRadialGradient(250, 50, 0, 250, 50, 50); // (x0, y0, r0, x1, y1, r1)gradientRadial.addColorStop(0, "rgba(242, 15, 231, 1)");gradientRadial.addColorStop(1, "rgba(64, 192, 214, 1)");ctx.fillStyle = gradientRadial;ctx.fillRect(200, 0, 100, 100);// 绘制图片填充方块const image = new Image();image.src = "https://www.ljynet.com/netImage/812688854_1707314089409.jpg";// 确保图片加载完成后再绘制image.onload = () => {ctx.drawImage(image, 300, 0, 100, 100);};
};// 页面挂载后才能绘制
onMounted(() => {drawCanvas();
});
</script>
<style lang="scss" scoped>
.canvasPage {width: 100%;height: 100vh;display: flex;justify-content: center;align-items: center;background-color: #dddddf;.main {width: 400px;height: 100px;}
}
</style>