簡體   English   中英

SVG 圖像未加載到 web-worker 中

[英]SVG Image not loaded in web-worker

我正在嘗試在網絡工作者中運行此打字稿代碼:

   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" 在此處輸入圖片說明

我也試過這個代碼:

   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-worker 中定義,因為它無法訪問 DOM。 然而,最后一種方法適用於非網絡工作者場景,但 createImageBitmap 不適用於任何地方。

任何人都知道如何在網絡工作者中從 SVG 構建和圖像,或者任何解決這種情況的方法?

謝謝

看到他們還沒有實現規范,

現在可能的解決方法是從主線程中的 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;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM