我希望在画布上放置图片。一开始我使用了图片作为背景,但每当我将画布转换为图像时,背景图片就无法被复制。因此,我尝试在画布上绘制图像。我从设备图像库中选择图像,将图像url存储为字符串并传递给下一个组件。我检查过了,能够获取该值。请参考以下代码,并告诉我我做错了什么。
1. HTML
<canvas no-bounce id="canvas"
(touchstart)='handleStart($event)' (touchmove)='handleMove($event)' (touchend)='handleEnd($event)' (click)="removeSelectedTxt()"
[ngStyle]="{
'width': '98%',
'height': '65%'}" #canvas ></canvas>
2. ts 文件
@ViewChild('canvas') public canvas: ElementRef;
ionViewDidLoad() {
console.log('ionViewDidLoad ImageHomePage');
this.canvasElement = this.canvas.nativeElement;
this.ctx = this.canvasElement.getContext('2d');
let image = this.renderer.createElement('img');
image.src = this.selectedImage;
this.ctx.drawImage(image,10, 10, this.canvasElement.width,
this.canvasElement.height);
}
我还使用了另一种方法...
方法2-
ionViewDidLoad() {
// this.selectedImage = this.route.snapshot.params['id'];
console.log('ionViewDidLoad ImageHomePage');
let canvasID= document.getElementById("canvas") as HTMLCanvasElement;
let canvasContext = canvasID.getContext("2d");
this.canvasElement = this.canvas.nativeElement;
this.ctx = this.canvasElement.getContext('2d');
let image = new Image() as HTMLImageElement;
image.onload = function() {
canvasContext.drawImage(image, 0, 0, canvasID.width, canvasID.height);
}
image.src = this.selectedImage;
}
请问我做错了什么?我知道这个问题已经被问过很多次了,我尝试了各种方法,但是都没有解决我的问题。因此,我想问一下这个问题,可能其他人将来也会遇到类似的问题。
this.selectedImage
是一个有效的 URL 吗?我怀疑这就是问题所在。 - Horace Lee