js 下载 canvas 兼容移动端

js 下载 canvas 兼容移动端

之前的下载方式

      let url = this.$refs.canvas.toDataURL("image/jpeg");
      let link = document.createElement("a");
      link.href = url;
      link.download = `拼接--${this.imageList[0].name}.jpg`;
      link.click();

移动端, uc/ 小米,  会一直在等待下载

 

采用blob的方式, 参考 MDN blob

其中也提供了polyfill方法

if (!HTMLCanvasElement.prototype.toBlob) {
 Object.defineProperty(HTMLCanvasElement.prototype, "toBlob", {
  value: function (callback, type, quality) {

    var binStr = atob( this.toDataURL(type, quality).split(",")[1] ),
        len = binStr.length,
        arr = new Uint8Array(len);

    for (var i=0; i<len; i++ ) {
     arr[i] = binStr.charCodeAt(i);
    }

    callback( new Blob( [arr], {type: type || "image/png"} ) );
  }
 });
}
this.$refs.canvas.toBlob(
  blob => {
    let link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    let filename = `拼接--${this.imageList[0].name}.jpg`;
    link.download = filename;
    link.filename = filename;
    link.click();
  },
  "image/jpeg",
  1 // [0,1] 表示图片质量
);

 

虽然文件名是乱码, 但是至少可以下载了.....