在vue3的uniapp小程序中使用Canvas画布

1,573 阅读1分钟

在uniapp+vue3中使用画布,你可以通过以下步骤来实现:

  1. 在页面的<template>中添加一个<canvas>元素。
  2. <script setup>中使用Composition API来创建画布上下文。
  3. 使用画布上下文的API绘制所需内容。

添加<canvas>元素

<template>
    <canvas id="MyCanvas" type="2d"></canvas>
</template>

获取canvas DOM元素,初始化画布

由于设备像素比的问题,画出的图形与预期不符,因此需要初始化画布大小

<script setup lang='ts'>
import { nextTick, getCurrentInstance } from 'vue'
    const instance = getCurrentInstance();
    nextTick(()=>{
        const query = uni.createSelectorQuery().in(instance?.proxy);
        query.select("#MyCanvas").fields({ node: true, size: true }, data => {
            const { node, width, height } = data
            // Canvas 对象
            const canvas = node
            // 渲染上下文
            const ctx = canvas.getContext('2d')
            // 初始化画布大小
            const dpr = uni.getWindowInfo().pixelRatio
            canvas.width = width * dpr
            canvas.height = height * dpr
            ctx.scale(dpr, dpr)
        }).exec();
    })
</script>

通过Canvas对象上下文绘制图形

            // 清除画布
            ctx.clearRect(0, 0, 300, 200);
            // 绘制图形
            ctx.fillStyle = 'red'
            ctx.fillRect(0, 0, 100, 100)