首页 > 解决方案 > Angular 6,而我试图在 2 个单独的画布元素上渲染相同的图像

问题描述

我得到的是图像仅在第二个画布上呈现,但我希望在两个画布上呈现相同的图像

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

在此处输入图像描述

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);
    };
  }


}

欢迎任何帮助。

标签: javascriptangularimagetypescript

解决方案


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


推荐阅读