Javascript 未在web worker中加载SVG图像
我正在尝试在web worker中运行此typescript代码:Javascript 未在web worker中加载SVG图像,javascript,html,typescript,chromium,web-worker,Javascript,Html,Typescript,Chromium,Web Worker,我正在尝试在web worker中运行此typescript代码: 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:
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);
}
但是现在的问题是,newimage()
对象没有在web worker中定义,因为它没有访问DOM的权限。不过,最后一种方法适用于非web工作者场景,但createImageBitmap在任何地方都不起作用
有人知道如何在web worker中构建SVG并从中生成图像,或者知道这种情况下的任何解决方法吗
感谢因为他们还没有实现规范 现在一个可能的解决方法是在主线程中从svg字符串生成一个图像,然后将生成的图像位图发布回工作线程 所以在主线程代码中
//异步加载SVG图像
函数加载svgasync(svgString)
返回新承诺(解决=>{
const img=新图像();
img.onload=函数(){
解决(这个问题);
};
img.src='data:image/svg+xml;charset=utf8',+encodeURIComponent(svgString);
});
}
常量工作者=新工作者(“…”);
worker.addEventListener('message',异步ev=>{
const YourSvgString='…';
const img=wait loadSVGAsync(您的svgstring);
//将图像位图传递给您的工作人员
postMessage({svg:await createImageBitMap(img)});
});
你的工人
self.addEventListener('message', (ev) => {
// Do whatever you need with the image
const svgImage = ev.data.svg;
});
看起来已将更新为允许。恐怕还没有浏览器实现这个功能?我也找不到一种方法让它工作。大多数浏览器都支持从加载在HTMLImageElement中的svg图像创建ImageBitmap,不需要OffscreenCavas,甚至不需要光栅化,只需postMessage
等待createImageBitmap(img)
,虽然您应该在代码中缺少的onload事件中执行此操作。您是对的@kaido,似乎我在测试时没有在SVG字符串中设置高度和宽度属性,这导致我使用屏幕外画布作为修补程序,而这恰好起到了作用。
self.addEventListener('message', (ev) => {
// Do whatever you need with the image
const svgImage = ev.data.svg;
});