Ionic React中如何获取图片的正确坐标
图片坐标标记偏差问题排查与解决
我正在开发一个基于Ionic React的移动端应用,核心功能是上传图片后标记坐标、为每个标记点添加文本,最终将带标记的内容上传至服务器。但下载图片后发现,捕获的坐标与实际标记位置偏差极大,推测是鼠标指针事件未能正确捕获图片内的坐标。
最初的图片指针捕获函数
const handleImageClick = (event: any) => { var e = event.target; const imageRect = e.getBoundingClientRect(); const x = event.clientX - imageRect.left; const y = event.clientY - imageRect.top; console.log(x,y) const newAnnotation: Annotation = { x, y, text: currentAnnotationText || 'New Annotation', }; setAnnotations([...annotations, newAnnotation]); setCurrentAnnotationText(''); };
前端渲染代码
<div className="image-container" style={{ position: 'relative' }}> <IonImg ref={imageRef} src={image} alt="Captured or Selected" style={{ marginBottom: '20px' }} onClick={handleImageClick} // Attach the onClick event directly to the IonImg /> {annotations.map((annotation, index) => ( <div key={index} className="annotation" style={{ position: 'absolute', top: `${annotation.y}px`, left: `${annotation.x}px`, backgroundColor: 'rgba(255, 255, 255, 0.7)', padding: '4px', borderRadius: '4px', }} > {annotation.text} </div> ))} </div>
问题解决方法
通过将坐标转换为百分比计算,成功解决了偏差问题。修改后的点击事件处理函数如下:
const handleImageClick = (event: any) => { const e = event.target as HTMLImageElement; const imageRect = e.getBoundingClientRect(); const x = ((event.pageX - imageRect.left) / imageRect.width) * 100; const y = ((event.pageY - imageRect.top) / imageRect.height) * 100; console.log(x, y); const newAnnotation: Annotation = { x, y, text: currentAnnotationText || 'New Annotation', }; setAnnotations([...annotations, newAnnotation]); setCurrentAnnotationText(''); };
内容的提问来源于stack exchange,提问作者meks285
相关产品推荐
相关产品推荐

