Skip to main content

Angular Konva 缓存教程

缓存会将节点光栅化为内部图像,这可以提高性能,并且是某些效果(例如滤镜)所必需的。

本示例在渲染后访问底层的 Konva 节点并手动调用 cache()

说明:演示展示了一个带有阴影样式的矩形,该矩形在视图初始化后被缓存。

了解更多详情,请参阅 Node API 参考cache() 文档

缓存示例

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { StageConfig } from 'konva/lib/Stage';
import { RectConfig } from 'konva/lib/shapes/Rect';

import {
  CoreShapeComponent,
  StageComponent,
} from 'ng2-konva';

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <ko-stage [config]="configStage">
      <ko-layer>
        <ko-rect #rect [config]="configRect"></ko-rect>
      </ko-layer>
    </ko-stage>
  `,
  imports: [StageComponent, CoreShapeComponent],
})
export default class App implements AfterViewInit {
  @ViewChild('rect') rect!: any;

  public configStage: StageConfig = {
    width: window.innerWidth,
    height: window.innerHeight,
  };
  public configRect: RectConfig = {
    x: 50,
    y: 50,
    width: 100,
    height: 100,
    fill: 'red',
    shadowBlur: 10,
    shadowColor: 'black',
    shadowOffsetX: 5,
    shadowOffsetY: 5
  };

  ngAfterViewInit() {
    if (this.rect) {
      this.rect.getNode().cache();
    }
  }
}