React在图片上在对应坐标上画点/框

一、需求

根据给出的坐标点(基于图片左上角为原点建立坐标系)以及宽高在图片上画框,数据格式为[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>

三、效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值