import { Component, Input, OnInit } from "@angular/core"; @Component({ selector: "app-img-look", templateUrl: "./img-look.component.html", styleUrls: ["./img-look.component.scss"], }) export class ImgLookComponent implements OnInit { @Input() data: any; constructor() {} imgUrl; ngOnInit(): void { console.log(this.data); this.imgUrl = this.data.itemData.ViolateImage; let dataArr = []; for (const key in JSON.parse(this.data.itemData.ViolatedItemSnapshot)) { const element = JSON.parse(this.data.itemData.ViolatedItemSnapshot)[key]; if (element.error) { dataArr.push(element); } } console.log("标绘坐标", dataArr); this.coordinate = dataArr; setTimeout(() => { this.canvasLabel(); }, 0); } canvasWidth = 0; canvasHeight = 0; ctx; coordinate; canvasLabel() { let imgBg: any = document.getElementById("img2"); imgBg.onload = () => { this.canvasWidth = imgBg.offsetWidth; this.canvasHeight = imgBg.offsetHeight; const img = new Image(); img.src = imgBg.src; img.onload = () => { const canvas: any = document.querySelector("#canvas2"); this.ctx = canvas.getContext("2d"); const cWidth = canvas.width, cHeight = canvas.height; // 以图画底 this.ctx.drawImage(img, 0, 0, cWidth, cHeight); this.strokeRect(this.coordinate); }; }; } strokeRect(data) { data.forEach((item) => { let startPoint = [ Math.round(this.canvasWidth * item.box[0]), Math.round(this.canvasHeight * item.box[1]), ]; let endPoint = [ Math.round(this.canvasWidth * item.box[2]), Math.round(this.canvasHeight * item.box[3]), ]; this.ctx.strokeStyle = "red"; this.ctx.lineWidth = 3; this.ctx.strokeRect( startPoint[0], startPoint[1], endPoint[0] - startPoint[0], endPoint[1] - startPoint[1] ); }); } }