Javascript 在图像上显示和选择边界框
给定边界框和图像的坐标,我希望在一个有角度的Web应用程序中在图像上显示可单击的边界框 目标是用户应选择一个或多个绘制在图像上的边界框,以便于标记 到目前为止,我只看到了带有HTML画布的可绘制边界框。但是,在我的例子中,已经存在多个边界框。我怎样才能完成这项任务 编辑:我曾尝试将两个画布元素层叠在一起,但是,我甚至无法显示图像,更不用说显示矩形了 component.html:Javascript 在图像上显示和选择边界框,javascript,html,angular,typescript,Javascript,Html,Angular,Typescript,给定边界框和图像的坐标,我希望在一个有角度的Web应用程序中在图像上显示可单击的边界框 目标是用户应选择一个或多个绘制在图像上的边界框,以便于标记 到目前为止,我只看到了带有HTML画布的可绘制边界框。但是,在我的例子中,已经存在多个边界框。我怎样才能完成这项任务 编辑:我曾尝试将两个画布元素层叠在一起,但是,我甚至无法显示图像,更不用说显示矩形了 component.html: 组件1.ts: 导出类AppComponent{ 公共imgWidth:编号; 公共照明:数字; 公共url
组件1.ts:
导出类AppComponent{
公共imgWidth:编号;
公共照明:数字;
公共url:string;
公众形象;
@ViewChild(“layer1”,{static:false})layer1Canvas:ElementRef;
私有上下文:CanvasRenderingContext2D;
私有层1画布元素:任何;
onSelectFile(事件){
if(event.target.files&&event.target.files[0]){
var reader=new FileReader();
reader.readAsDataURL(event.target.files[0]);
reader.onload=事件=>{
this.image=新图像();
this.image.src=reader.result;
this.image.onload=()=>{
this.imgWidth=this.image.width;
this.imgHeight=this.image.height;
这是showImage();
};
};
}
}
showImage(){
this.layer1CanvasElement=this.layer1Canvas.nativeElement;
this.context=this.layer1CanvasElement.getContext(“2d”);
this.context.drawImage(this.image,this.imgWidth,this.imgHeight);
this.drawRect();
}
drawRect(){
this.context.beginPath();
this.context.rect(200300400500);
this.context.lineWidth=10;
this.context.strokeStyle=“black”;
this.context.stroke();
}
}
Stackblitz链接
预览
步骤01
- 除去
width={{imgWidth}} height={{imgHeight}}
- 加
this.layer1CanvasElement.width = this.imgWidth; this.layer1CanvasElement.height = this.imgHeight;
- 从
this.context.drawImage(this.image,this.imgWidth, this.imgHeight);
- 到
this.context.drawImage(this.image, 0, 0, this.imgWidth, this.imgHeight);
- 添加mousemove事件侦听器
this.layer1CanvasElement.addEventListener("mousemove", function(e) {})
- 确定点是否为
(PointX,PointY)
- 属于矩形
(RectangleX,RectangleY,RectangleWidth,RectangleHeight)
- 利用
(RectangleX <= PointX <= RectangleX + RectangleWidth) (RectangleY <= PointY <= RectangleY + RectangleHeight)
(RectangleX你可以使用一个名为Annotorious的工具。我用它在Angular 8中为图像添加注释。该工具是根据BSD许可证授权的。非常容易使用。你可以下载源代码并编辑小部件,如果你想的话。非常棒的工具。
添加您尝试过的代码并尝试在stackblitz上创建演示谢谢,我以前应该这样做。做了更多的研究并尽了最大努力,直到我卡住为止;在这里添加了stackblitz演示和相关代码。答案解决了您的问题吗?如果解决了,您可以共享代码吗?非常感谢,这对我有很大帮助。我不得不从c改过来lientX/Y从MouseMove事件中偏移x/Y,否则会突出显示错误的框。但是,这对性能有很大的影响,因为有几百个边界框,因此负载很大。let x = 200; let y = 300; let w = 400; let h = 500; if ( x <= e.clientX && e.clientX <= x + w && y <= e.clientY && e.clientY <= y + h ) drawRect("red"); else drawRect("black"); });