简体   繁体   中英

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. 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 file

@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-

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 ..

Below is my code..

I called below function in 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. Without setTimeout it wasn't showing any thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM