简体   繁体   中英

unable to load image from assets folder in angular

I have a big problem. I am Unable to load image onto canvas from assets folder in angular.

html code

<div class="container-fluid">
    <div class="row">
        <div class="col-md-8 canvas-viewer">
            <canvas width="240" height="297" style="border:1px solid #d3d3d3;" id="crfCanvas" #crfCanvas></canvas>
        </div>
        <div class="col-md-4 canvas-anno">

        </div>
    </div>
</div>

component.ts code

export class CanvasComponent implements OnInit {

  @ViewChild("crfCanvas", { static: true }) crfCanvas: ElementRef;
  constructor() { }

  ngOnInit() {
    let canvas = this.crfCanvas.nativeElement;
    let ctx = canvas.getContext("2d");
    let img = new Image();
    img.src = "../../assets/aCRF-PRV111_CLN-001 v1.4-images/aCRF-PRV111_CLN-001 v1.4-blank_0.jpg";
    ctx.drawImage(img, 10, 10, 250, 250);
  }

}

A few things needs to be considered:

  1. ViewChild binds to the view, so its best to await for the view to finish initialization (use ngAfterViewInit hook), but ngOnInit will also work (it is just if you would need in future to consider offsets etc for drawing into canvas it might bite you:)

  2. Image loading is an async task, you need to leverage onload hook before you attempt to draw the image

  3. Use "/assets/.." urls to avoid issues

Updated code:

export class CanvasComponent implements OnInit {

  @ViewChild("crfCanvas", { static: true }) crfCanvas: ElementRef;

  constructor() { }

  ngAfterViewInit() {
    let canvas = this.crfCanvas.nativeElement;
    let ctx = canvas.getContext("2d");
    let img = new Image();
    img.src = "/assets/aCRF-PRV111_CLN-001 v1.4-images/aCRF-PRV111_CLN-001 v1.4-blank_0.jpg";
    img.onload = () => {
        ctx.drawImage(img, 10, 10, 250, 250);
    }
  }

}

Stackblitz: https://stackblitz.com/edit/angular-v5tqbn

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