【vue3】使用canvas

本文介绍了HTML5 canvas的基本用法,包括如何在HTML中创建和使用canvas元素,获取CanvasRenderingContext2D对象,以及通过JavaScript进行绘图,如直线、矩形、弧线和图形的基本操作。同时展示了在Vue3中应用canvas的方法,涵盖了折线、矩形绘制和路径控制。
该文章已生成可运行项目,

canvas是什么?

一个html5支持的新标签,见名知意,canvas就是画板的意思,可以在canvas上画画。css画三角形很简单,但是要画五角星呢,不妨试试canvas。

在html中使用canvas

1、canvas是html5中的一个标签。

新建一个html。并在body中加入canvas标签。

<body>
    <canvas height="600" width="600"></canvas>
</body>

此时canvas已经显示在画板中,只不过因为和body的颜色一样,所以看不出来。

在head中加入css样式。

<style>
    canvas {
        border:1px solid;
    }
</style>

这时我们就可以看到canvas了。

在这里插入图片描述

2、获取CanvasRenderingContext2D对象用于绘图。

先给canvas一个id属性,

<canvas id='canvas' height="600" width="600"></canvas>

获取。

<script>
  const ctx=document.querySelector('#canvas').getContext('2d');
</script>

注意,script标签应该在body标签后(至少在canvas标签后),只有在canvas渲染后才能通过JavaScript代码获取到canvas中的CanvasRenderingContext2D对象。

<body>
    <canvas height="600" width="600"></canvas>
</body>
<script>
  const ctx=document.querySelector('.canvas').getContext('2d');
</script>

3、使用JavaScript代码进行绘画。

<script>
  const ctx=document.querySelector('#canvas').getContext('2d');
  ctx.moveTo(100,100);
  ctx.lineTo(100,400);
  ctx.stroke();
</script>

该代码绘制了一条直线。

在这里插入图片描述

关于CanvasRenderingContext2D对象更多的绘制方法请参考官方文档。至少现在我们知道canvas是如何使用的了。(一定要注意要在渲染完成后才能通过JavaScript代码获取CanvasRenderingContext2D对象)

在vue3中使用canvas

1、创建vite+vue3项目并运行。

npm init vue@latest

在这里插入图片描述

2、创建我们的canvas。

这是我们的App.vue文件

<script setup>

</script>

<template>

</template>

<style scoped>

</style>

创建我们的canvas

<script setup>

</script>

<template>
  <canvas height="600" width="600"></canvas>
</template>

<style scoped>
canvas {
  border: 1px solid;
}
</style>

在这里插入图片描述

3、获取CanvasRenderingContext2D对象并绘制直线。

给canvas标签添加一个ref属性

<canvas ref='canvas' height="600" width="600"></canvas>

获取canvas对象

<script setup>
import {ref} from 'vue'
const canvas = ref();
</script>

渲染完成后获取CanvasRenderingContext2D对象

<script setup>
import { onMounted, ref } from 'vue'

const canvas = ref();

onMounted(() => {
  const ctx = canvas.value.getContext('2d'); 
})

</script>

画一条直线

<script setup>
import { onMounted, ref } from 'vue'

const canvas = ref();

onMounted(() => {
  const ctx = canvas.value.getContext('2d');
  ctx.moveTo(100, 100);
  ctx.lineTo(100, 400);
  ctx.stroke();  
})

</script>

在这里插入图片描述

4、模板

<script setup>
import { onMounted, ref } from 'vue'

const canvas = ref();
let ctx = ref();

const drawLine = () => {
  ctx.moveTo(100, 100);
  ctx.lineTo(100, 400);
  ctx.stroke();
}

const initContext = () => {
  ctx = canvas.value.getContext('2d');
}

onMounted(() => {
  initContext();
  drawLine();
})

</script>

<template>
  <canvas ref='canvas' height="600" width="600"></canvas>
</template>

<style scoped>
canvas {
  border: 1px solid;
}
</style>

canvas快速入门

绘制折线

一个moveTo配合多个lineTo。可以通过lineWidth设置线宽,还可以设置两个端点和转折处的形状(使用lineCap和lineJoin)

// 使用moveTo,lineTo,lineWidth,lineCap,lineJoin
const drawCurvedLine = () => {
  ctx.moveTo(100, 100);
  ctx.lineTo(400, 100);
  ctx.lineTo(100, 400);
  ctx.lineTo(400, 400);
  ctx.lineCap = 'round';
  ctx.lineJoin = 'round';
  ctx.stroke();
}

绘制矩形

rect方法以及strokeRect和fillRect。效果等效:strokeRect=rect+stroke,fillRect=rect+stroke。

绘制方式:绘制边框,使用stroke,绘制填充,使用fill。strokeStyle可以设置边框颜色,fillStyle可以设置填充颜色。

// 使用rect,srokeStyle,stroke,fillStyle,fill
const drawStrokeRect = () => {
  ctx.rect(100, 100, 100, 100);
  ctx.strokeStyle = 'green';
  ctx.stroke();
}

const drawFillRect = () => {
  ctx.rect(300, 100, 100, 100);
  ctx.fillStyle = 'blue';
  ctx.fill();
}

将绘制一个绿色边框的矩形和蓝色的矩形。然而,当一同调用时,会发现变成了两个一模一样的矩形(绿色边框或者蓝色填充)。

属性作用域:解决上述问题,使用beginPath方法即可。beginPath将后面对于属性的设置隔离开来,以避免覆盖前面的属性。

// 这里还尝试了使用strokeRect和fillRect替代了rect、stroke、fill
const drawStrokeRect = () => {
    ctx.beginPath();
    ctx.strokeStyle='green';
    ctx.strokeRect(100,100,100,100);
}

const drawFillRect = () => {
  ctx.beginPath();
  ctx.fillStyle = 'blue';
  ctx.fillRect(300, 100, 100, 100);
}

绘制弧线

圆圈

ctx.beginPath();
ctx.arc(100,75,50,0,2*Math.PI);
ctx.stroke();

圆弧

ctx.beginPath();
ctx.arc(100,75,50,90/180*Math.PI,2*Math.PI);
ctx.stroke();

扇形

ctx.beginPath();
ctx.moveTo(100,75);
ctx.arc(100,75,50,90/180*Math.PI,2*Math.PI);
ctx.closePath();
ctx.fill();

圆环

  const RINGWIDTH = 10;

  ctx.beginPath();
  ctx.arc(100, 75, 90, 0, 2 * Math.PI);
  ctx.fill();
  ctx.beginPath();
  ctx.arc(100, 75, 90-2*RINGWIDTH, 0, 2 * Math.PI);
  ctx.fillStyle = 'white';
  ctx.fill();

补充:

  • 如你所见,绘制扇形时使用了closePath,意思是将所有端点连接起来(一般是将终点和起点连接起来,形成一个闭合图形。只有图形闭合时,fill才能生效)。
  • 所有函数的参数不需要单位。(设置字体时,ctx.font=‘40px’,需要带单位,但确实不是函数的参数)
  • 需要角度作为参数时,都是以弧度的形式提供。计算公式,弧度=角度*Math.PI/180。90度,记为90*Math.PI/180。
  • 更多关于画布的使用,可以查看HTML Canvas 参考手册 (w3school.com.cn)
本文章已经生成可运行项目
### Vue3使用 Canvas 的方法 在 Vue3 中集成和使用 Canvas 是一种常见的需求,无论是绘制图形、处理图像还是创建动态效果,Canvas 都能提供强大的支持。以下是基于提供的参考资料以及专业知识整理的内容。 #### 1. 基础设置 为了在 Vue3使用 Canvas,首先需要在一个组件中定义 `<canvas>` 元素并获取其上下文对象 `ctx`。通过该对象可以调用各种绘图 API 来操作画布[^3]。 ```html <template> <div> <canvas ref="myCanvas"></canvas> </div> </template> <script> import { ref, onMounted } from &#39;vue&#39;; export default { setup() { const myCanvas = ref(null); onMounted(() => { const canvas = myCanvas.value; const ctx = canvas.getContext(&#39;2d&#39;); // 设置画布大小 canvas.width = window.innerWidth; canvas.height = window.innerHeight; // 示例:绘制矩形 ctx.fillStyle = &#39;#FF5733&#39;; ctx.fillRect(50, 50, 150, 100); }); return { myCanvas }; }, }; </script> ``` 上述代码展示了如何初始化一个简单的 Canvas 并在其上绘制一个填充颜色的矩形。 --- #### 2. 动态交互功能 如果希望实现更复杂的动态效果,例如粒子涟漪特效,则可以通过监听事件来更新画布上的内容。以下是一个简化版的粒子动画示例: ```html <template> <div> <canvas ref="rippleCanvas" @click="handleClick"></canvas> </div> </template> <script> import { ref, onMounted } from &#39;vue&#39;; export default { setup() { const rippleCanvas = ref(null); let particles = []; const handleClick = (event) => { const mouseX = event.offsetX; const mouseY = event.offsetY; for (let i = 0; i < 10; i++) { particles.push(new Particle(mouseX, mouseY)); } }; class Particle { constructor(x, y) { this.x = x; this.y = y; this.size = Math.random() * 5 + 1; this.speedX = Math.random() * 3 - 1.5; this.speedY = Math.random() * 3 - 1.5; this.alpha = 1; } update(ctx) { this.x += this.speedX; this.y += this.speedY; this.alpha -= 0.01; if (this.alpha > 0) { ctx.globalAlpha = this.alpha; ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2); ctx.fill(); } } } onMounted(() => { const canvas = rippleCanvas.value; const ctx = canvas.getContext(&#39;2d&#39;); canvas.width = window.innerWidth; canvas.height = window.innerHeight; function animate() { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); particles.forEach((particle, index) => { particle.update(ctx); if (particle.alpha <= 0) { particles.splice(index, 1); } }); } animate(); }); return { rippleCanvas, handleClick }; }, }; </script> ``` 这段代码实现了点击画布时生成随机移动的粒子效果[^4]。 --- #### 3. 结合第三方库扩展功能 对于一些特定场景,如绘制复杂图案或二维码,可以借助现有的插件或工具包完成开发工作。例如,在 Vue3 中利用 `vue-drawing-canvas` 插件快速构建绘画界面[^1];或者按照引用中的方式生成二维码[^2]。 ```javascript mounted() { const canvas = this.$refs.canvas; const ctx = canvas.getContext(&#39;2d&#39;); import QRCode from &#39;qrcode&#39;; // 引入 qrcode 库 QRCode.toDataURL(&#39;https://www.example.com&#39;, { errorCorrectionLevel: &#39;M&#39; }, (err, url) => { if (err) throw err; const img = new Image(); img.onload = () => { ctx.drawImage(img, 0, 0, canvas.width, canvas.height); }; img.src = url; }); } ``` 以上片段说明了如何结合外部依赖项(QRCode.js)向 Canvas 添加自动生成的二维码图片。 --- #### 总结 综上所述,Vue3 提供了一个灵活且高效的框架环境用于管理 DOM 节点及其状态变化,而 HTML5 Canvas 则赋予开发者自由操控像素级渲染的能力。两者相结合能够创造出丰富多彩的应用程序体验。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值