当我尝试在2个单独的画布元素上渲染相同图像时为Angular 6

时间:2018-06-27 19:49:35

标签: javascript angular image typescript

我得到的是图像仅在第二个画布上渲染 但我想在两个画布上渲染相同的图像

此屏幕快照显示图像仅在第二个画布上呈现

enter image description here

HTML组件

<div fxLayout="row" fxLayoutAlign="center center">
  <canvas #canvas1 id="ctx1" width="500" height="500" style="border: 1px solid dodgerblue;"></canvas>
  <canvas #canvas2 id="ctx2" width="500" height="500" style="border: 1px solid #83ff1e;"></canvas>
</div>

打字稿组件

import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, AfterViewInit {

  @ViewChild('canvas1') canvas1: ElementRef;
  @ViewChild('canvas2') canvas2: ElementRef;

  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit() {
    this.init();
  }

  init() {
    const img = new Image();
    img.src = '../../../assets/img/lena_color.png';

    const width = 500;
    const height = 500;

    const canvas1: HTMLCanvasElement = this.canvas1.nativeElement;
    const ctx1: CanvasRenderingContext2D = canvas1.getContext('2d');

    const canvas2: HTMLCanvasElement = this.canvas2.nativeElement;
    const ctx2: CanvasRenderingContext2D = canvas2.getContext('2d');

    console.log(ctx1);
    console.log(ctx2);


    this.drawImage(ctx1, img);
    this.drawImage(ctx2, img);

  }


  drawImage(ctx, img) {
    img.onload = () => {
      ctx.drawImage(img, 0, 0);
    };
  }


}

欢迎任何帮助。

1 个答案:

答案 0 :(得分:1)

定义两个Image对象,而不是重复使用同一对象。