uni-app在image上绘制点位并回显

news/2025/1/13 18:31:13/

在 Uni-app 中绘制多边形可以通过使用 Canvas API 来实现。Uni-app 是一个使用 Vue.js 开发所有前端应用的框架,同时支持编译为 H5、小程序等多个平台。由于 Canvas 是 H5 和小程序中都支持的 API,所以通过 Canvas 绘制多边形是一个比较通用的方法。

1. 创建一个新的 Uni-app 项目(如果还没有的话)

vue create -p dcloudio/uni-preset-vue my-uni-app
cd my-uni-app

2. 开始绘制

背景:在image上绘制多边形,并将点位回传。回传后的数据格式'(1,2),(3,4)',所以需要一些方法进行处理。如你没有转换需求,可自行删除。

<template><view class="layout-wrap"><view class="draw-wrap"><view class="camera-wrap"><img:style="{ width: `${canvasWidth}px`, height: `${canvasHeight}px` }":src="cameraUrl"mode="aspectFill"class="popup-img"/><canvasid="myCanvas"canvas-id="myCanvas"@touchstart="onTouchStart"@touchend="onTouchEnd":style="{ width: `${canvasWidth}px`, height: `${canvasHeight}px` }"></canvas></view></view><view class="btn-wrap"><view class="btn reset-btn" @click="handleClear">清 除</view><view class="btn" @click="handleSubmit">确 定</view></view></view>
</template><script>
import { addCameraRegion, getCameraId } from "@/api/cabinet";
import config from "@/config";
const baseUrl = config.baseUrl;
export default {name: "draw",data() {return {points: [], // 存储触摸点canvasWidth: "",canvasHeight: "",ctx: "",cameraUrl: "",rate: "",touchNum: 0,};},onShow() {this.init();},methods: {init() {// 获取配置及绘制图形getCameraId(config.hostInfoId).then((res) => {const data = res.data;this.monitorPoints = data.monitorPoints;this.rate =  data.monitorWidth / data.monitorHeight;this.canvasWidth = 1000this.canvasHeight = this.canvasWidth / this.rate;this.cameraUrl =baseUrl +"/api/monitor/player?cameraId=" +data.monitorCameraId +"&time=" +new Date().getTime();const ctx = uni.createCanvasContext("myCanvas");this.ctx = ctx;this.touchNum = 0this.setRect();});},onTouchStart(e) {if (this.touchNum === 0) {this.handleClear()}this.touchNum++;const touch = e.touches[0];this.points.push({ x: touch.x, y: touch.y });},onTouchEnd(e) {this.drawPolygon();this.ctx.draw();},drawPolygon() {const ctx = this.ctx;ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight); // 清除画布ctx.setStrokeStyle("#00ff00"); // 设置多边形边框颜色// 设置填充样式和透明度ctx.setLineWidth(10); // 设置多边形边框宽度ctx.beginPath();this.points.forEach((point, index) => {if (index === 0) {ctx.moveTo(point.x, point.y);} else {ctx.lineTo(point.x, point.y);}});// 如果需要闭合多边形,取消注释以下行ctx.closePath();ctx.stroke();// 绘制填充ctx.setFillStyle("rgba(0, 255, 0, 0.4)");ctx.fill();},// 根据之前的数据回显多边形(如果有的话)setRect() {try {const pointsArr = this.monitorPoints.slice(1, -1).split("),(");if (pointsArr && pointsArr.length > 1) {pointsArr.map((p) => {this.points.push({x: Math.round(p.split(",")[0] / this.rate),y: Math.round(p.split(",")[1] / this.rate),});});console.log(this.canvasWidth, this.canvasHeight);console.log(this.points);this.drawPolygon();setTimeout(() => {//必须延迟执行 不然H5不显示this.ctx.draw(); //必须加上  uniapp 没这儿玩意儿 显示不出来不比原生  不加可以显示}, 200);}} catch (error) {console.error("绘制多边形时出错:", error);}},// 提交    handleSubmit() {if (this.points.length > 1) {// 转换并发送多边形的顶点坐标const scaledPoints = [];this.points.map((point) => {scaledPoints.push(`(${Math.round(point.x * this.rate)},${Math.round(point.y * this.rate)})`);});// 提交请求} else {uni.showToast({title: "请绘制",icon: "none",});}},// 清除handleClear() {this.points = [];this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight); // 清除画布this.ctx.draw();},},
};
</script>
<style lang="scss" scoped>
.draw-wrap {position: relative;margin-top: 2vh;left: 7vw;
}
.camera-wrap {height: 76vh;
}
.popup-img {position: absolute;top: 0;left: 0;object-fit: contain;border: 6rpx solid #093763;box-sizing: border-box;
}#myCanvas {position: absolute;top: 0;left: 0;
}
</style>

3. 效果图

4. 解释

  • uni.createCanvasContext('myCanvas') 用于获取 Canvas 的绘图上下文。
  • ctx.setStrokeStyle('red') 和 ctx.setLineWidth(10) 用于设置描边颜色和宽度。
  • ctx.beginPath() 开始一个新的路径。
  • ctx.moveTo(points[0].x, points[0].y) 和 ctx.lineTo(points[i].x, points[i].y) 用于绘制线段。
  • ctx.closePath() 闭合路径,使之成为一个多边形。
  • ctx.stroke() 描边。
  • ctx.setFillStyle('rgba(30, 144, 255,0.5)') 和 ctx.fill() 用于填充多边形。
  • ctx.draw() 将所有绘图操作提交到 Canvas 上。

5. 坑

回显的时候,苦恼了很久,为什么点位已经传入,不能回显。后来发现,是draw方法需要加延时。


http://www.ppmy.cn/news/1554419.html

相关文章

element plus的switch开关回显

element plus的switch开关通过 :model-value"" 是绑定值&#xff0c;必须等于 active-value 或 inactive-value&#xff0c;默认为 Boolean 类型 :active-value"2" 是switch 状态为 on 时的值 :inactive-value"1" 是switch的状态为 off 时的…

期末复习-计算机网络篇SCAU

第一章&#xff1a;概述 1.计算机网络的特点&#xff0c;互联网发展的三个阶段 特点&#xff1a;连通性、资源共享 三个阶段&#xff1a; 1969-1990&#xff1a;从单个网络ARPANET向互联网发展 1985-1993&#xff1a;建成了三级结构的互联网 1993-现在&#xff1a;全球范…

浅析OCR技术与大模型的深度融合—中安未来OCR产品优势及前景探索

OCR&#xff08;光学字符识别&#xff09;技术作为一种文本识别工具&#xff0c;已在文档管理、自动化办公和图书数字化等领域发挥了重要作用。然而&#xff0c;随着深度学习和大语言模型&#xff08;LLM&#xff09;的迅猛发展&#xff0c;OCR技术迎来了新的机遇和挑战。如今&…

KV Shifting Attention Enhances Language Modeling

基本信息 &#x1f4dd; 原文链接: https://arxiv.org/abs/2411.19574&#x1f465; 作者: Mingyu Xu, Wei Cheng, Bingning Wang, Weipeng Chen&#x1f3f7;️ 关键词: KV shifting attention, induction heads, language modeling&#x1f4da; 分类: 机器学习, 自然语言处…

调度系统:使用 Airflow 对 Couchbase 执行 SQL 调度时的潜在问题

使用 Airflow 对 Couchbase 执行 SQL 调度时&#xff0c;通常情况下不会直接遇到与 Couchbase 分布式特性相关的异常&#xff0c;但在某些特定情境下&#xff0c;可能会出现一些与分布式环境、调度和数据一致性相关的潜在问题。以下是一些可能会遇到的问题和建议的解决方案&…

创客匠人十一月总结|持续高能量赋能,为IP发展注入新活力

随着时间流转&#xff0c;寒意渐深&#xff0c;时光的脚步悄无声息地迈向了下一个崭新的节点。对于创客匠人来说&#xff0c;十一月是创新与挑战并重的一个月&#xff0c;也是收获与突破共舞的一个月。 创客匠人作为“知识变现整体解决方案服务商”&#xff0c;我们始终认为自己…

Vue导出报表功能【动态表头+动态列】

安装依赖包 npm install -S file-saver npm install -S xlsx npm install -D script-loader创建export-excel.vue组件 代码内容如下&#xff08;以element-ui样式代码示例&#xff09;&#xff1a; <template><el-button type"primary" click"Expor…

SkyWalking 和 ELK 链路追踪实战

一、背景 最近在给项目搭建日志平台的时候&#xff0c;采用的方案是 SkyWalking ELK 日志平台&#xff0c;但发现 ELK 日志平台中的日志没有 Trace ID&#xff0c;导致无法追踪代码报错的整体链路。 空哥提示&#xff1a;Trace ID 是分布式追踪中用来唯一标识一个服务请求或事…