Angular6 - canvas.drawImage()不工作
我想把图像放在画布上.最初我使用图像作为背景.但是每当我将画布转换为图像时,背景图像都不会被复制.因此,我尝试在画布上绘制图像.我正在从设备图片库中选择图片.将图像 url 存储为字符串并传递给下一个组件.我检查了,能够获得价值.请看下面的代码,让我知道我做错了什么.
I want to put image on canvas. initially I used image as background. But whenever I convert canvas to image, background image is not getting copied. Hence I tried to draw image on canvas. I am choosing image from device image gallery. Storing the image url as string and passing to next component. I checked, able to get the value. Please see below code and let me know what I did wrong.
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);
}
我也用了另一种方式……
I used another way also...
方法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;
}
我可以知道,我做错了什么吗?我知道这个问题已经被问过很多次了,我尝试了这些方法,但没有一个对我有用..因此问这个问题,可能其他人将来会面临问题..
May I know, what am I doing wrong? I know this question has been asked so many times, I tried the methods but none of them worked for me.. Hence asking the question, might be others will face issue in future..
推荐答案
终于解决了问题..
我添加了 Renderer 2
..
下面是我的代码..
我在 ionViewDidload()
let newImg = this.renderer.createElement('img');
newImg.src = this.selectedImage;
newImg.onload = this.drawImg(newImg);
drawImg(imgContext){
console.log('drawImg called');
setTimeout(() => {
this.ctx.drawImage(imgContext,0,0, this.canvasElement.width, this.canvasElement.height);
}, 1000);
}
我调用了 setTimeout
因为它需要时间.没有 setTimeout
它什么也没有显示.
I called setTimeout
because it was taking time. Without setTimeout
it wasn't showing any thing.
相关文章