[英]Angular6 - canvas.drawImage() not working
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.
将图像URL存储为字符串并传递给下一个组件。 I checked, able to get the value.
我检查过,能够得到价值。 Please see below code and let me know what I did wrong.
请看下面的代码,让我知道我做错了什么。
1. HTML 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 file 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... 我用另一种方式也......
Method 2- 方法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..
我知道这个问题已被问了很多次,我尝试了这些方法,但没有一个对我有效。因此提出问题,可能是其他人将来会面临问题。
Finally I solved issue.. 最后我解决了问题..
I added Renderer 2
.. 我添加了
Renderer 2
..
Below is my code.. 以下是我的代码..
I called below function in ionViewDidload()
我在
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);
}
I called setTimeout
because it was taking time. 我调用了
setTimeout
因为它需要时间。 Without setTimeout
it wasn't showing any thing. 没有
setTimeout
它没有显示任何东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.