【问题标题】:Canvas toDataURL return empty画布 toDataURL 返回空
【发布时间】:2021-04-22 00:57:06
【问题描述】:

我正在尝试使用 Canvas 将 SVG 元素导出为图像 blob。当我尝试调用 canvas.toDataURL("image/png") 它返回空字符串。我无法弄清楚为什么会发生这种情况。

const svg: Node = document.getElementById("flowchart-container").children[0];
var icanvas = document.getElementById("stage");
const ctx: CanvasRenderingContext2D = icanvas.getContext("2d");
var width = (svg as HTMLElement).clientWidth;
var height = (svg as HTMLElement).clientHeight;
const image: HTMLImageElement = document.createElement("img");
image.crossOrigin = "anonymous";
const imageBlob: Blob = new Blob(
  [new XMLSerializer().serializeToString(svg)],
  {
    type: "image/svg+xml",
  }
);
const blobUrl: string = URL.createObjectURL(imageBlob);
image.src = blobUrl ;
image.onload = (): void => {
  //ctx.clearRect(0, 0, width, height);
  ctx.drawImage(image, 0, 0, width, height);
  window.URL.revokeObjectURL(blobUrl);
  try {
    const imageData: string = icanvas.toDataURL("image/png");
    const imageFileToBeExported: Blob | File = this.dataURLtoFile(
      imageData,
      "flowchart.png"
    );
    promiseResolve(imageFileToBeExported);
  } catch (error) {
    console.log('Failed to Create Image');
    console.log(error);
    promiseReject(error);
  }
};

以上代码位于 createSVG 方法中。 caller 是显示方法。

    public createSVG(
        promiseResolve: (data: File | Blob) => void,
        promiseReject: (error: unknown) => void
        ): void {
        //Code for Creating File
    }

public async getImage() :Promise<any>{
    let imageBlob: File | Blob;
    try {
        imageBlob = await generateImageAsynchronously();
    } catch (error) {
      console.log('Failed to create Image');
    }
}

public generateImageAsynchronously(): Promise<File | Blob> {
    return new Promise(
      (
        resolver: (data: File | Blob) => void,
        reject: (error: unknown) => void
      ): void => {
        this.createSVG(resolver, reject);
      }
    );
}

终于调用了下面的方法

public display(){
    this.getImage().then(response => {
      console.log('Resolving Promise');
      this.imageBlob = response;
    );
}

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    这是使用 .onload 时的常见问题,基本上您是在处理数据之前返回承诺。 您可以尝试将其包装在这样的异步函数中

    async function waitForloading(){
    let waitForLoad = await processImage()
    return waitForLoad
    }
    
    function processImage(){
    return new Promise(function(promiseResolve,promiseReject){
    const svg: Node = document.getElementById("flowchart-container").children[0];
    var icanvas = document.getElementById("stage");
    const ctx: CanvasRenderingContext2D = icanvas.getContext("2d");
    var width = (svg as HTMLElement).clientWidth;
    var height = (svg as HTMLElement).clientHeight;
    const image: HTMLImageElement = document.createElement("img");
    image.crossOrigin = "anonymous";
    const imageBlob: Blob = new Blob(
      [new XMLSerializer().serializeToString(svg)],
      {
        type: "image/svg+xml",
      }
    );
    const blobUrl: string = URL.createObjectURL(imageBlob);
    image.src = blobUrl ;
    image.onload = (): void => {
      //ctx.clearRect(0, 0, width, height);
      ctx.drawImage(image, 0, 0, width, height);
      window.URL.revokeObjectURL(blobUrl);
      try {
        const imageData: string = icanvas.toDataURL("image/png");
        const imageFileToBeExported: Blob | File = this.dataURLtoFile(
          imageData,
          "flowchart.png"
        );
        promiseResolve(imageFileToBeExported);
      } catch (error) {
        console.log('Failed to Create Image');
        console.log(error);
        promiseReject(error);
      }
    };
    )}
    }
    

    【讨论】:

    • 即使使用异步也无法正常工作。当我尝试记录 icanvas.toDataURL("image/png") 的输出时,我得到 - ,
    • 这是由于 SVG 元素内部存在异物导致跨域问题。
    猜你喜欢
    • 2015-01-03
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 2012-11-30
    • 2015-09-20
    相关资源
    最近更新 更多