Angular6 - canvas.drawImage()不起作用 [英] Angular6 - canvas.drawImage() not working

查看:448
本文介绍了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..

推荐答案

最后我解决了问题..

Finally I solved issue..

我添加渲染器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.

这篇关于Angular6 - canvas.drawImage()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆