一、需求
根据给出的坐标点(基于图片左上角为原点建立坐标系)以及宽高在图片上画框,数据格式为[x, y, width, height], 且都是基于图片真实大小的百分比。
二、实现
1、计算出真实的坐标点和宽高
公式:actualX = x*renderedWidth,actualY = y*renderedHeight, actualWidth = width*renderedWidth, actualHeight = height*renderedHeight
具体函数代码如下:
其中imageDimensions里width和height是图片原始大小,在图片加载的时候获得,
而图片渲染的实际大小则通过imageRef获得,为imgRef.current.offsetWidth。
function getRenderedImageSize(src) {
const img = new Image();
let width = null;
let height = null;
img.onload = function() {
width = this.width;
height = this.height;
const scale = Math.min(imgRef.current.offsetWidth/width, imgRef.current.offsetHeight/height);
setImageDimensions({width: width, height: height, naturalWidth: imgRef.current.offsetWidth, naturalHeight: imgRef.current.offsetHeight, scale: scale})
};
img.src = src;
}
整体的渲染组件如下:
其中picConf是根据后台接口返回的格式为[[x1, y1, w1, h1], [x2, y2, w2, h2], [x3, y3, w3, h3]]的array,根据该array的长度画多个方框。
<div style={{ position: "relative" }}>
<img ref={imgRef} style={{ width: "100%" }} src={imageUrl} />
{/* 使用动态生成的CSS类来定位矩形 */}
{picConf.map((picConf, index) => (
<div
key={index}
className={`marker-${index}`}
style={{
position: "absolute",
left: `${picConf[0] * imageDimensions.naturalWidth}px`,
top: `${picConf[1] * imageDimensions.naturalHeight}px`,
width: `${picConf[2] * imageDimensions.naturalWidth}px`,
height: `${picConf[3] * imageDimensions.naturalHeight}px`,
backgroundColor: "none",
border: "2px solid red",
zIndex: 1,
}}
></div>
))}
</div>