SVG图像未加载到网络工作者中

问题描述 投票:4回答:1

我正在尝试在网络工作者中运行此打字稿代码:

   async BuildImage(): Promise<void> {

    let data1 = `<svg xmlns='http://www.w3.org/2000/svg' width='50' height='50'>
                    <foreignObject width='100%' height='100%' style="background:blue">
                      <div xmlns='http://www.w3.org/1999/xhtml' style='font-size:12px'>                        
                        <ellipse cx="23" cy="23" rx="25" ry="25" style="fill:yellow;stroke:purple;stroke-width:2" />
                      </div>
                    </foreignObject>
                  </svg>`;

    let svg = new Blob([data1], { type: "image/svg+xml;charset=utf-8" });
    var image = await createImageBitmap(svg);

}

但是用"The source image could not be decoded."抛出"InvalidStateError"enter image description here

我也尝试过此代码:

   async BuildImage(): Promise<void> {

    let data1 = `<svg xmlns='http://www.w3.org/2000/svg' width='50' height='50'>
                    <foreignObject width='100%' height='100%' style="background:blue">
                      <div xmlns='http://www.w3.org/1999/xhtml' style='font-size:12px'>                        
                        <ellipse cx="23" cy="23" rx="25" ry="25" style="fill:yellow;stroke:purple;stroke-width:2" />
                      </div>
                    </foreignObject>
                  </svg>`;

    let svg = new Blob([data1], { type: "image/svg+xml;charset=utf-8" });
    let url = URL.createObjectURL(svg);

    var loadImageAsync = new Promise<HTMLImageElement>(resolve => {

        let img = new Image();
        img.onload = () => resolve(img);
        img.onerror = () => resolve(img);

        img.src = url;
    });

    this.image = await loadImageAsync;}

但是现在的问题是new Image()对象没有在Web工作者中定义,因为它无权访问DOM。但是,这最后一种方法在非网络工作者的情况下可用,但是createImageBitmap在任何地方都无法使用。

任何人都知道如何在Web-Worker中使用SVG进行构建和映像,或针对这种情况的任何解决方法?

谢谢

javascript html typescript chromium web-worker
1个回答
0
投票

由于他们尚未执行该规范,

目前一种可能的解决方法是从主线程中的svg字符串生成图像,然后将生成的图像位图发布回给工作人员。

所以在您的主线程代码中

// Loads the SVG image asynchronously
function loadSVGAsync(svgString) 
 return new Promise(resolve => {
  const img = new Image();
  img.onload = function () {
    resolve(this);
  };
  img.src = 'data:image/svg+xml;charset=utf8,' + encodeURIComponent(svgString);
 });
}

const worker = new Worker('...');

worker.addEventListener('message', async ev => {
 const YourSvgString = '...';

 const img = await loadSVGAsync(YourSvgString);

 // Pass over the image Bit map to your worker
 worker.postMessage({svg: await createImageBitMap(img)});
});

在你的工人中

self.addEventListener('message', (ev) => {
  // Do whatever you need with the image
  const svgImage = ev.data.svg;
});
© www.soinside.com 2019 - 2024. All rights reserved.