HTML中动态调整area标签大小的实现方案求点评
动态调整图片映射区域(area)的coords属性方案
开发交互式图片功能时,发现area标签的映射区域无法随图片尺寸动态变化,于是写了一段动态修改coords属性的代码,想问问大家的看法:
const getArea = document.querySelectorAll("area"); const getimg = document.querySelector(".myImg"); getArea.forEach(function (area) { const scaleWidth = getimg.width / getimg.naturalWidth; const scaleHeight = getimg.height / getimg.naturalHeight; coords = area.coords.split(","); const x = coords[0]; const y = coords[1]; const width = coords[2]; const height = coords[3]; area.coords = `${x*scaleHeight},${y*scaleWidth},${width* scaleWidth},${height* scaleHeight}`; });
几点看法和优化建议:
- 核心思路可行:通过计算当前图片与原始尺寸的缩放比例,对coords的数值进行等比缩放,能解决area区域不随图片缩放的问题。
- 缩放比例对应错误:x是水平坐标,应该用
scaleWidth计算;y是垂直坐标,应该用scaleHeight计算,现在的写法会导致宽高缩放比例不同时,映射区域出现变形。修正后应该是:area.coords = `${x*scaleWidth},${y*scaleHeight},${width*scaleWidth},${height*scaleHeight}`; - 补充变量声明:
coords没有用let/const声明,会成为全局变量,建议改为let coords = area.coords.split(",");。 - 增加触发时机:这段代码需要在图片加载完成后执行,否则
naturalWidth/naturalHeight可能获取不到正确值;如果图片是响应式的,还要在窗口resize事件中重新执行,保证coords随图片尺寸实时更新。 - 兼容更多shape类型:当前代码只处理了
rect类型的area(coords为4个值),如果有circle(3个值:x,y,r)或poly(多组x,y坐标)的area,需要根据area.shape属性做不同的逻辑处理,比如circle要缩放x、y和半径r,poly要遍历每一组坐标对进行缩放。
内容的提问来源于stack exchange,提问作者amjadmak
相关产品推荐
相关产品推荐

