从零开始学习在VUE3中使用canvas(一):实现一个基础的canvas画布

一、步骤

1.写一个canvas元素

2.获取虚拟dom

3.获取绘制环境

4.绘制想要的效果

5.在挂载后执行

二、代码

html 复制代码
<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>

三、效果

下一篇:从零开始学习在VUE3中使用canvas(二):fillStyle(填充样式)-CSDN博客

相关推荐
dear_bi_MyOnly7 分钟前
【MyBatis 操作数据库】
java·数据库·学习·mybatis·学习方法
一只小菜鸡..1 小时前
南京大学 操作系统 (JYY) 学习笔记:从 UNIX 到 Linux 与庞大的应用生态
笔记·学习·unix
东方小月2 小时前
从零开发一个 Coding Agent(四):使用状态机校验大模型事件流
前端·人工智能·后端
Csvn2 小时前
🧩 ESM vs CJS 混用的 7 个「天坑」——从 TypeScript 编译到 Node 与浏览器
前端
Csvn2 小时前
🎯 Web 性能 API 集合:Performance Observer 的 5 个冷门妙用
前端
MartinYeung52 小时前
[论文学习]迈向自主医疗人工智能智能体:MIRA系统深度分析
人工智能·学习
Csvn2 小时前
深入 React 闭包陷阱:从根源上理解并根治 stale closure
前端
whyfail2 小时前
前端学 Spring Boot(8):接口为什么越用越慢?
前端·spring boot·后端
用户059540174463 小时前
LangChain 记忆测试踩坑实录:这两个坑让我排查了 4 小时
前端·css
程序员黑豆3 小时前
鸿蒙应用开发:@Monitor 装饰器使用教程
前端·harmonyos