错误TypeError:fs.​​createWriteStream不是函数Angular 6 GIF导出

时间:2019-05-28 09:30:26

标签: javascript html angular typescript canvas

我创建了以下函数来创建GIF,我想将其导出到.gif图像中。

import * as gifEncoder from 'gif-encoder';

animate() {
    var canvas: HTMLCanvasElement = this.canvas.nativeElement;
    var context = canvas.getContext('2d');
    var gif = gifEncoder;
    gif = new gifEncoder(10, 10);

    if (this.numberOfFrames < this.points.length - 1) {
        requestAnimationFrame(() => this.animate());
    }
    else {
        console.log("Program End Reached...");
        gif.finish();
        this.gif = gif;
    }

    context.beginPath();
    var fromX = this.points[this.numberOfFrames - 1].x;
    var fromY = this.points[this.numberOfFrames - 1].y;
    var toX = this.points[this.numberOfFrames].x;
    var toY = this.points[this.numberOfFrames].y;
    context.lineWidth = 5;
    context.strokeStyle = "red";
    context.moveTo(fromX, fromY);
    context.lineTo(toX, toY);
    context.stroke();
    gif.writeHeader();
    gif.addFrame(context);

    this.numberOfFrames++;  
}

然后我有一个按钮可以将该画布内容导出到GIF文件。

downloadAsGIF() {
    let fs = require('fs');
    var file = fs.createWriteStream('img.gif');
    this.gif.pipe(file);
}

错误:

ERROR TypeError: fs.createWriteStream is not a function

我要去哪里错了?任何帮助将不胜感激。我正在使用this tutorial

1 个答案:

答案 0 :(得分:0)

实际上,它将在服务器端运行。浏览器没有fs。因此,您必须使用浏览器支持的其他一些库。

也就是说,这是客户端JS的答案。

使用

  

使用BrowserFS.configure(),您可以轻松配置BrowserFS以使用   多种文件系统类型。

     

这是一个使用LocalStorage支持的文件的简单用法示例   系统:

<script type="text/javascript" src="browserfs.min.js"></script>
<script type="text/javascript">
  // Installs globals onto window:
  // * Buffer
  // * require (monkey-patches if already defined)
  // * process
  // You can pass in an arbitrary object if you do not wish to pollute
  // the global namespace.
  BrowserFS.install(window);
  // Configures BrowserFS to use the LocalStorage file system.
  BrowserFS.configure({
    fs: "LocalStorage"
  }, function(e) {
    if (e) {
      // An error happened!
      throw e;
    }
    // Otherwise, BrowserFS is ready-to-use!
  });
</script>

可以轻松地像这样使用:

var fs = require('fs');
fs.writeFile('/test.txt', 'Cool, I can do this in the browser!', function(err) {
  fs.readFile('/test.txt', function(err, contents) {
    console.log(contents.toString());
  });
});