<template> <view> <!-- 定义canvas画布 // 设置canvas大小为200x200像素 --> <canvas @touchstart="handleCanvasTouch" canvas-id="canvas" id="canvas" style="border: 1px solid red;height: 600px;width: 100vw;"></canvas> <!-- 添加一个按钮,用于触发绘图 --> <button @click="handleDraw">点击绘制圆形</button> </view> </template> <script setup> import { ref, onMounted, getCurrentInstance } from 'vue' const canvasWidth = ref(375) // 动态设置Canvas宽度 const canvasHeight = ref(400) // 动态设置Canvas高度 const instance = getCurrentInstance() // 定义绘图函数 const blocks = ref([{ x: 50, y: 50, width: 100, height: 100, color: 'red', message: '点击了红色方块' }, { x: 200, y: 50, width: 100, height: 100, color: 'blue', message: '点击了蓝色方块' }, { x: 50, y: 200, width: 100, height: 100, color: 'green', message: '点击了绿色方块' }, { x: 200, y: 200, width: 100, height: 100, color: 'yellow', message: '点击了黄色方块' }, { x: 350, y: 50, width: 100, height: 100, color: 'purple', message: '点击了紫色方块' }, ]) async function draw() { const imgUrl = "https://assets.sx25.troyrc.com/sx25/images/events/XBDT.jpg" const ctx = uni.createCanvasContext('canvas', instance) // 创建canvas绘图上下文 const res = await uni.getImageInfo({ src: imgUrl, }) console.log(res, 'res'); ctx.drawImage(res.path, 0, 0, canvasWidth.value, canvasHeight.value); // 定义5个方块的颜色和位置 // 绘制每个方块 blocks.value.forEach((block) => { ctx.beginPath(); ctx.fillStyle = block.color; ctx.rect(block.x, block.y, block.width, block.height); ctx.fill(); }); ctx.draw() } // 处理canvas触摸事件 function handleCanvasTouch(event) { // 获取触摸点的坐标 const x = event.touches[0].x; const y = event.touches[0].y; // 定义5个方块的颜色和位置 // 判断点击位置 blocks.value.forEach((block) => { if (x >= block.x && x <= block.x + block.width && y >= block.y && y <= block.y + block.height) { uni.showModal({ title: '提示', content: block.message, showCancel: true, // 显示取消按钮 success: (res) => { if (res.confirm) { console.log('用户点击了“确定”按钮'); } else if (res.cancel) { console.log('用户点击了“取消”按钮'); } }, }); } }); } // 按钮点击事件处理函数 const handleDraw = () => { draw(); // 调用绘图函数 } onMounted(() => { draw() // 确保在组件挂载后可以获取到Canvas元素 }) </script> <style scoped> button { margin-top: 10px; } </style>