一、步骤
1.写一个canvas元素
2.获取虚拟dom
3.获取绘制环境
4.绘制想要的效果
5.在挂载后执行
二、代码
<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 = 100;
canvas.height = 100;
// 获取Canvas绘制2D环境
const ctx = canvas.getContext("2d");
if (!ctx) return console.error("无法获取CanvasRenderingContext2D");
// 定义后面绘制的图形的颜色
ctx.fillStyle = "red";
// 绘制矩形(矩形左上角坐标x,y,宽度,高度)
ctx.fillRect(0, 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: 100px;
height: 100px;
}
}
</style>
三、效果