canvas在鼠标单击事件时获取图像像素点



我在项目中使用画布,并将图片设置为画布背景,我希望当我点击图像区域时,我能获得原始像素点所以我想把画布堇青石转换成像素堇青石

在typescript中定义画布:

context: CanvasRenderingContext2D;
@ViewChild( 'myCanvas' ) canvas: ElementRef;
ngAfterViewInit() {
const canvas = this.canvas.nativeElement;
let context=canvas.getContext( '2d' );
var background = new Image();
background.src = "assets/media/products/1.png";
background.crossOrigin = "anonymous";
background.onload = function(){
context.drawImage(background,0,0, canvas.width, canvas.height);
}
this.context= context
this.cdr.detectChanges()

}

并以html:显示画布

<canvas #myCanvas id="canvas"  (click)="clickPosition($event)"></canvas>
clickPosition(event: MouseEvent) {
console.log("X  = " + event.offsetX);
console.log("Y = " + event.offsetY);
}

event.offsetX显示cordinate屏幕大小,但我想获得图像像素,对于这个问题,我使用getImageData((但是我没有收到正确的数据

尝试此函数-element.getBoundingClientRect((

相关内容

  • 没有找到相关文章

最新更新