Angular 2 - 导入html2canvas

时间:2017-04-07 07:39:16

标签: node.js angular import npm html2canvas

我已使用html2canvasangular 2项目上安装了npm install html2canvas --save。如果我现在转到任何文件并写import * as html2canvas from 'html2canvas',则会出错:

Cannot find module 'html2canvas'

我的包文件如下所示:

{
  ...
  "scripts": {
    ...
  },
  "dependencies": {
    ...
    "html2canvas": "^0.5.0-beta4",
    ...
  },
  "devDependencies": {
    ...
  }
}

我尝试导入html2canvas的文件是:

import { Injectable } from '@angular/core';
import * as jsPDF from 'jspdf';
import * as html2canvas from 'html2canvas';

@Injectable ()
export class pdfGeneratorService {

  ...
}

4 个答案:

答案 0 :(得分:3)

由于Angular2使用typescript,您需要安装该模块的typescript定义文件。

可以从@types安装(如果存在)。如果不是,您可以创建自己的定义文件并将其包含在项目中。

答案 1 :(得分:2)

在角度9中,我以这种方式使用它:

import html2canvas from 'html2canvas';
....
    html2canvas(this.head2print.nativeElement).then(_canvas => {
      hdr = _canvas.toDataURL("image/png");
    });

答案 2 :(得分:1)

此外,回调函数的 onrendered 选项可能无效。相反,你可以使用"然后"如下:

html2canvas(document.body).then((canvas) => {
  document.body.appendChild(canvas);
});

https://stackoverflow.com/a/45366038/3119507

答案 3 :(得分:0)

在运行Angular 8时遇到同样的问题。在安装 @types 后仍然无法正常工作。对我有用的是改为使用require来包含html2canvas库。

const html2canvas = require('../../../node_modules/html2canvas');

然后获取屏幕截图:

       @ViewChild('screenshotCanvas') screenCanvas: ElementRef;

       html2canvas(this.screenCanvas.nativeElement).then(canvas => {
            var imgData = canvas.toDataURL("image/png");
            console.log("ENTER takeScreenshot: ",imgData )
            document.body.appendChild(imgData);
        })