图片热区功能

2024-02-02 12:04
文章标签 功能 图片 热区

本文主要是介绍图片热区功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、需求描述及效果图

1.需求描述:

根据后端返回的坐标及人员信息,在图片上的相应位置添加图片热区功能,点击可展示出对应的人员信息。
图片可进行缩放

2.示例:

(定位是随便写的,仅做示例)
鼠标悬浮到坐标位置上会出现水波纹的效果,点击定位处出现信息框来描述定位位置的信息。
image.png

二、思路

1.使用结合设置图片热区

官网地址:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area

代码示例:
image.png

2.数据结构
{"code": 0,"data": {"picture": "base64字符串","personnel": [{"id": 1,"personCode": "code_9527","personName": "nameA","personCard": "320123199901011234","personPhone": "13777777777","personPosition": "position01","personTail": 175,"personWeight": 70,"registerCamera": "Y","imgPath": "/home/picData/test_9527.jpg","coordinate": {"x": 10,"y": 20,"width": 100,"height": 100}},{"id": 2,"personCode": "code_10000","personName": "nameB","personCard": "320123199901022234","personPhone": "13777777777","personPosition": "position01","personTail": 190,"personWeight": 120,"registerCamera": "Y","imgPath": "/home/picData/test_10000.jpg","coordinate": {"x": 10,"y": 20,"width": 100,"height": 100}}]},"message": "请求成功!","time": 0
}
  • props.imageUrl是父组件传递过来的图片地址,上面数据结构中的picture
  • state.areaMap是人员信息数组,上面数据结构中的personnel
  • 数据结构中的coordinate是坐标信息,x和y是热区左上角的坐标;因为热区是矩形的,需要知道左上角和右下角的坐标,需根据热区的宽高来计算出右下角的坐标(热区形状根据需求来定,不唯一)
3.计算坐标
3.1 图片原始尺寸和渲染尺寸

需要获取到图片的原始固定尺寸和渲染的尺寸,从而计算出宽高的比例来正确定位
image.png

  • 图片原始尺寸:
// 图片原始尺寸
const naturalWidth = ref(0);
const naturalHeight = ref(0);
// 获取el-image组件实例的根DOM元素,也就是<img>元素,从而获取到图片的原始宽高
const imgEl = imageRef.value?.$el.querySelector('img');if (imgEl) {naturalHeight.value = imgEl.naturalHeight;naturalWidth.value = imgEl.naturalWidth;}

获取el-image组件实例的根DOM元素,元素,从而获取到图片的原始宽高

const imgEl = imageRef.value?.$el.querySelector('img');

注意:确保在组件已正确渲染并挂载到DOM树上之后再尝试获取img元素,以避免在组件尚未准备好时获取null值

  • 图片渲染尺寸:
  const renderWidth = imageRef.value?.$el.clientWidth;const renderHeight = imageRef.value?.$el.clientHeight;
3.2 根据缩放比例重新计算坐标

根据图片的原始尺寸和渲染尺寸计算出缩放比

  // 计算比例const ratioWidth = renderWidth / naturalWidth.value;const ratioHeight = renderHeight / naturalHeight.value;

根据缩放比重新计算热区

const imageRef = ref<any>(null);
const naturalWidth = ref(0);
const naturalHeight = ref(0);// 计算图片缩放比例
function ratioPic() {// 获取图片的原始尺寸const imgEl = imageRef.value?.$el.querySelector('img');console.log('imgEl', imageRef.value, imgEl.value)if (imgEl) {naturalHeight.value = imgEl.naturalHeight;naturalWidth.value = imgEl.naturalWidth;}// 图片渲染大小const renderWidth = imageRef.value?.$el.clientWidth;const renderHeight = imageRef.value?.$el.clientHeight;// 计算宽高缩放比例const ratioWidth = renderWidth / naturalWidth.value;const ratioHeight = renderHeight / naturalHeight.value;// 重新计算热区state.areaMap = [];state.initAreaMap.map((item) => {const obj = {...item,coordinate: {...item.coordinate,width: Math.round(item.coordinate.width * ratioWidth),height: Math.round(item.coordinate.height * ratioHeight),x: Math.round(item.coordinate.x * ratioWidth),y: Math.round(item.coordinate.y * ratioHeight),},};state.areaMap.push(obj);});
}

initAreaMap 存放的时候从接口获取的图片热区坐标数据
areaMap 存放经过缩放比计算后的图片热区新坐标(计算时注意要置空)

3.3 监听窗口尺寸变化,实时调整热区
onMounted(async () => {// 添加窗口尺寸变化的监听以实时调整热区window.addEventListener('resize', handleResize);
});onUnmounted(() => {window.removeEventListener('resize', handleResize);
});// 监听屏幕变化重新计算图片热区宽高
function handleResize() {// 在这里获取图片当前的实际尺寸,并重新计算热区坐标ratioPic();
}
3.4 处理矩形坐标: 左上角 ,右下角
function handleCoordinate(coordinate: Coordinate) {const x2 = coordinate.x + coordinate.width;const y2 = coordinate.y + coordinate.height;return `${coordinate.x},${coordinate.y},${x2},${y2}`;
}

因为后端返回的坐标数据是图片热区的左上角坐标和宽高,在使用时需计算出右下角坐标
矩形热区需要坐标:(左上角x,y 右下角x,y)
coords=“x1, y1, x2, y2”

以上,浏览器自带的缩放功能可正确渲染出热区; 如果需要对图片进行放大和缩小功能,对热区坐标的处理请看下面第4点【图片缩放功能】

4.图片缩放功能

Element Plus的组件可通过 previewSrcList 开启预览大图功能可对图片进行放大缩小
image.png但是这个功能并没有提供方法进行其他操作,所以根据需求我放弃使用previewSrcList,重写了一个图片预览缩放功能。
image.png

4.1 遮罩层及图片缩放组件

通过对scaleVisible的控制来打开/关闭遮罩层和图片预览
是图片缩放组件的内容,将图片地址及人员信息传递过去
image.png
样式设置:
注意层级关系

// 遮罩层样式
.mask {// 相对于浏览器窗口进行定位,全屏遮住position: fixed; top: 0;left: 0;width: 100%;height: 100%;background-color: #808080;opacity: 0.5;z-index: 8888;
}
// 遮罩层上的关闭按钮
.mask_close {position: fixed;right: 40px;top: 40px;width: 50px;height: 50px;cursor: pointer;z-index: 10000;
}
// 图片缩放组件
.pic_scale {position: fixed;top: 0;left: 0;width: 100%;height: 100%;z-index: 9999;display: flex;justify-content: center;align-items: center;
}
4.2 缩放工具栏

image.png

.flow-toolbar-wrap {position: absolute;bottom: 30px;width: 100%;display: flex;align-items: center;justify-content: center;.flow-toolbar {display: flex;align-items: center;justify-content: center;gap: 10px;height: 40px;box-shadow: var(--el-box-shadow-light);background-color: #66686b;opacity: 0.8;border-radius: 20px;padding: 0 25px;z-index: 1;.toolbar-item {user-select: none;color: #fff;font-size: 20px;cursor: pointer;}}
}
4.4 计算缩放比
const state = reactive({areaMap: [] as PicInfo[],initAreaMap: [] as PicInfo[],scale: 1, // 图片缩放比例originWidth: 0,originHeight: 0,
});// 放大操作
function toolbarZoomIn() {state.scale = Number((state.scale + 0.1).toFixed(1));applyZoom();
}
// 缩小操作
function toolbarZoomOut() {if (state.scale === 0.7) return;state.scale = Number((state.scale - 0.1).toFixed(1));applyZoom();
}
// 1.图片加载完成之后再去计算宽高,避免网络请求被延迟或阻塞导致尺寸无法获取。
function imgOnLoad() {ratioPic();state.originWidth = imageRef.value?.$el.clientWidth;state.originHeight = imageRef.value?.$el.clientHeight;
}
// 计算经过缩放后的宽高 
function applyZoom() {// 2.整体放大图片外层盒子和图片const divEl = document.querySelector('.scaleImage') as HTMLElement;divEl.style.transform = `scale(${state.scale})`;divEl.style.width = `${state.originWidth * state.scale}px`;divEl.style.height = `${state.originHeight * state.scale}px`;// 3.重新计算热区,同前面的3.2的操作ratioPic();
}

注意点:

  1. 要在图片加载完成之后再去计算宽高,避免网络请求被延迟或阻塞导致尺寸无法获取
  2. 放大/缩小时要整体放大/缩小外层盒子和图片
4.5鼠标滚动缩放
onMounted(async () => {// 添加鼠标滚动缩放const mapEl = document.querySelector('.scaleImage') as HTMLElement;mapEl.addEventListener('mousewheel', (e) => {if (e instanceof WheelEvent) {e.preventDefault(); // 阻止默认的滚轮行为,如页面滚动const delta = Math.sign(e.deltaY);// 根据滚动方向和步长调整缩放比例if (delta > 0) {toolbarZoomIn();} else {toolbarZoomOut();}}});
});
5.添加热区样式及信息框样式
5.1 热区样式

设置鼠标悬浮到热区范围内时的样式:两个圈的水波纹效果
image.png
样式:

:deep(.areaHighlight) {/* 设置高亮区域的背景颜色和透明度等样式 */pointer-events: none; /* 防止覆盖原始交互 */width: 50px;height: 50px;position: relative;
}:deep(.areaHighlight)::before,
:deep(.areaHighlight)::after {position: absolute;content: '';width: 100%;height: 0;padding-bottom: 100%; /* 设置为宽度的百分比,实现宽高比为1:1 */top: 0;left: 0;background: #a5d7ff;border-radius: 50%;animation: animLoader 2s linear infinite;
}:deep(.areaHighlight)::after {animation-delay: 1s;opacity: 0.1;
}
// 水波纹动画
@keyframes animLoader {0% {transform: scale(0);opacity: 1;}100% {transform: scale(1);opacity: 0;}
}

利用鼠标的移入和移出事件来添加样式
image.png

// 热区高亮
function highlightArea(area: any) {const overlay = document.createElement('div');overlay.style.position = 'absolute';// 根据area.shape和area.coords计算并设置overlay的位置和尺寸overlay.id = `overlay-${area.personCode}`;overlay.style.left = `${area.coordinate.x}px`;overlay.style.top = `${area.coordinate.y}px`;overlay.style.width = `${area.coordinate.width}px`;overlay.style.height = `${area.coordinate.height}px`;overlay.classList.add('areaHighlight');mapContainer.value?.appendChild(overlay);
}
// 移除高亮
function removeHighlight() {const overlayDiv = document.querySelectorAll('.areaHighlight');overlayDiv.forEach((item) => {mapContainer.value?.removeChild(item);});
}
5.2 信息框动画效果
.model_scale {display: none;position: absolute;width: 35%;min-width: 300px;max-width: 350px;border-radius: 10px;z-index: 2;color: #fff;border: 2px solid gold;border-radius: 10px;background: #ffd700;transition: all 0.3s;
}
// 边框动画
.model_scale::before {content: '';position: absolute;top: -10px;left: -10px;right: -10px;bottom: -10px;border: 2px solid #ffd700;border-radius: 10px;animation: borderAni 3s infinite linear;
}.model_scale::after {content: '';position: absolute;top: -10px;left: -10px;right: -10px;bottom: -10px;border: 2px solid #ffd700;border-radius: 10px;animation: borderAni 3s infinite linear;
}@keyframes borderAni {0%,100% {clip-path: inset(0 0 98% 0);}25% {clip-path: inset(0 98% 0 0);}50% {clip-path: inset(98% 0 0 0);}75% {clip-path: inset(0 0 0 98%);}
}.model_scale::after {animation: borderAni 3s infinite -1.5s linear;
}
.model_close {position: absolute;top: -15px;right: -15px;width: 30px;height: 30px;cursor: pointer;z-index: 3;
}
.model_content {color: #000;font-size: 13px;
}

image.png

// 点击热区
function areaClick(area: any) {// 获取要展示的信息personnelInfo.forEach((item: InfoList) => {item.value = area[item.key] ?? '';});// 打开信息框,定位const modelEl = document.querySelector('.model_scale') as HTMLElement;modelEl.style.display = 'block';modelEl.style.left = area.coordinate.x + 100 + 'px';modelEl.style.top = area.coordinate.y + 50 + 'px';
}// 关闭信息框
function closeModel() {const modelEl = document.querySelector('.model_scale') as HTMLElement;modelEl.style.display = 'none';
}

三、遇到的问题

1.无法正确获取图片到宽高时,值为0

问题描述: 在浏览器中,通过JavaScript获取图片(元素)的宽高属性时,在某些情况下可能会获取不到正确的值或者得到0

  1. 异步加载:浏览器加载网页时,HTML文档结构优先于外部资源(如图片、样式表和脚本)。当JavaScript代码执行时,如果图片尚未完全加载完成,则其naturalWidth或clientWidth等尺寸属性可能还未被浏览器填充,因此返回值为0。
  2. 事件监听不足:为了确保能够获取到图片的真实尺寸,应当在图片加载完成后触发一个事件处理函数,比如使用onload事件来确保图片已经加载完毕。
  3. 调试器影响:虽然不常见,但在极少数情况下,打开浏览器调试器并刷新页面可能导致渲染过程中的细微差别,这可能是由于强制重新布局(relayout)或重绘(repaint)引起的。如果你是在DOMContentLoaded或load事件触发之前就尝试获取图片尺寸,并且同时打开了调试器,那可能由于网络请求被延迟或阻塞导致尺寸无法获取。
  4. 缓存问题:有时候,特别是开发环境下,浏览器缓存可能导致实际图片未被重新加载,因此onload事件没有触发,尺寸信息也就无法更新。

此处我是遇到了第三个问题:打开调试器时无法正确获取图片宽高。

解决方法:确保在图片加载完成后才去读取其尺寸属性,或者是使用Promise或者async/await方式来等待图片加载完成。

使用load方法
image.png
在图片加载完成之后再去操作

// 图片加载完成之后再去计算宽高,避免网络请求被延迟或阻塞导致尺寸无法获取。
function imgOnLoad() {ratioPic();state.originWidth = imageRef.value?.$el.clientWidth;state.originHeight = imageRef.value?.$el.clientHeight;
}
2.图片在缩放时,外层div无法和图片一样大导致信息框等样式产生定位错误

如果在缩放时只控制图片的放大和缩小,缩放到一定程度时图片外层的div无法和图片的DOM元素一样大,且基于外层div进行定位的元素定位会产生误差

解决方法:
1.计算图片元素和外层div缩放产生的误差值,在计算坐标时加上误差值
2.缩放时直接对外层div进行缩放,需让图片和外层div保持一样的宽高

这里我选择了第二种方式

function applyZoom() {/*   const imgEl = imageRef.value?.$el.querySelector('img');imgEl.style.transform = `scale(${state.scale})`;imgEl.style.width = `${state.originWidth * state.scale}px`;imgEl.style.height = `${state.originHeight * state.scale}px`; */// 整体放大图片外层盒子和图片const divEl = document.querySelector('.scaleImage') as HTMLElement;divEl.style.transform = `scale(${state.scale})`;divEl.style.width = `${state.originWidth * state.scale}px`;divEl.style.height = `${state.originHeight * state.scale}px`;ratioPic();
}

这篇关于图片热区功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/670645

相关文章

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Spring框架5 - 容器的扩展功能 (ApplicationContext)

private static ApplicationContext applicationContext;static {applicationContext = new ClassPathXmlApplicationContext("bean.xml");} BeanFactory的功能扩展类ApplicationContext进行深度的分析。ApplicationConext与 BeanF

JavaFX应用更新检测功能(在线自动更新方案)

JavaFX开发的桌面应用属于C端,一般来说需要版本检测和自动更新功能,这里记录一下一种版本检测和自动更新的方法。 1. 整体方案 JavaFX.应用版本检测、自动更新主要涉及一下步骤: 读取本地应用版本拉取远程版本并比较两个版本如果需要升级,那么拉取更新历史弹出升级控制窗口用户选择升级时,拉取升级包解压,重启应用用户选择忽略时,本地版本标志为忽略版本用户选择取消时,隐藏升级控制窗口 2.

Android 10.0 mtk平板camera2横屏预览旋转90度横屏拍照图片旋转90度功能实现

1.前言 在10.0的系统rom定制化开发中,在进行一些平板等默认横屏的设备开发的过程中,需要在进入camera2的 时候,默认预览图像也是需要横屏显示的,在上一篇已经实现了横屏预览功能,然后发现横屏预览后,拍照保存的图片 依然是竖屏的,所以说同样需要将图片也保存为横屏图标了,所以就需要看下mtk的camera2的相关横屏保存图片功能, 如何实现实现横屏保存图片功能 如图所示: 2.mtk

Spring MVC 图片上传

引入需要的包 <dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.1</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-

Spring+MyBatis+jeasyui 功能树列表

java代码@EnablePaging@RequestMapping(value = "/queryFunctionList.html")@ResponseBodypublic Map<String, Object> queryFunctionList() {String parentId = "";List<FunctionDisplay> tables = query(parent

Prompt - 将图片的表格转换成Markdown

Prompt - 将图片的表格转换成Markdown 0. 引言1. 提示词2. 原始版本 0. 引言 最近尝试将图片中的表格转换成Markdown格式,需要不断条件和优化提示词。记录一下调整好的提示词,以后在继续优化迭代。 1. 提示词 英文版本: You are an AI assistant tasked with extracting the content of

PostgreSQL核心功能特性与使用领域及场景分析

PostgreSQL有什么优点? 开源和免费 PostgreSQL是一个开源的数据库管理系统,可以免费使用和修改。这降低了企业的成本,并为开发者提供了一个活跃的社区和丰富的资源。 高度兼容 PostgreSQL支持多种操作系统(如Linux、Windows、macOS等)和编程语言(如C、C++、Java、Python、Ruby等),并提供了多种接口(如JDBC、ODBC、ADO.NET等