将Canvg 3.0与Angular项目集成

时间:2019-12-09 11:12:50

标签: angular canvg

在当前开发的应用程序中,我正在使用canvg库在页面中进行一些画布渲染,直到现在,我都使用canvg 2.0库以以下方式实现此目的:

import Canvg from 'canvg/dist/browser/canvg.min.js';

// convert SVG into a XML string
xml = new XMLSerializer().serializeToString(obj);
// Removing the name space as IE throws an error
xml = xml.replace(/xmlns=\"http:\/\/www\.w3\.org\/2000\/svg\"/, '');
// draw the SVG onto a canvas
Canvg(canvas, xml);

几天前,发布了Canvg版本3,该版本将所有内容更改为Typescript,而canvg.min.js不再存在,我找不到在Angular 8项目中集成已安装npm的canvg库的方法,因此我可以使用像以前一样,没有为“ Canvg”功能导入任何模块的建议,并且该文档对于如何将其与Angular集成也没有帮助。

有人遇到此问题,并且知道如何解决吗?

2 个答案:

答案 0 :(得分:1)

如果他们已经迁移到TypeScript,实际上会更容易。他们在 here 中提供了一些文档。

这是一个让您入门的示例:

import { Component, ViewChild, AfterViewInit, OnDestroy } from "@angular/core";
import Canvg from "canvg";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit, OnDestroy {
  @ViewChild("canvas", { static: false }) canvas;
  context: CanvasRenderingContext2D;
  renderedCanvas;

  async ngAfterViewInit() {
    this.context = this.canvas.nativeElement.getContext("2d");
    this.renderedCanvas = await Canvg.from(
      this.context,
      '<svg width="600" height="600"><text x="50" y="50">Hello World!</text></svg>'
    );
    this.renderedCanvas.start();
  }

  ngOnDestroy() {
    this.renderedCanvas && this.renderedCanvas.stop();
  }
}

这是模板:

<canvas #canvas></canvas>

  

这里是Sample Code Example供您参考。

答案 1 :(得分:0)

调用import * as canvg from 'canvg'后,可以使用npm install canvg --save导入canvg