是否可以使用某些屏幕外画布从服务工作者创建动态生成的图像?
我可以想象它是一种非常新的技术,如果它存在这样的东西,但我发现在创建画布的规范中没有任何来源......是否有可能在任何实验性标志后面的任何浏览器甚至一些讨论/问题它?
答案 0 :(得分:3)
对于firefox,可以在worker中使用的非常方便的API是OffscreenCanvas
答案 1 :(得分:0)
用于在服务工作者中使用OffscreenCanvas生成即时通知图像的代码示例:
// canvas.toDataURL() not available with OffscreenCanvas ?
const toDataURL = async (data) =>
new Promise(ok => {
const reader = new FileReader();
reader.addEventListener('load', () => ok(reader.result));
reader.readAsDataURL(data);
});
const imageCanvas = async (title) => {
const canvas = new OffscreenCanvas(192, 192);
const ctx = canvas.getContext('2d');
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText(title, canvas.width/2, canvas.height/2);
// Hack-ish
const blob = await canvas.convertToBlob();
return await toDataURL(blob);
};
self.addEventListener("push", event =>
event.waitUntil(Promise.resolve().then(async() => {
let body, image;
if (self.OffscreenCanvas) image = await imageCanvas('Hello Push');
else body = 'Your Browser does not support OffscreenCanvas with Service Worker';
console.log('[SW]', { image });
return self.registration.showNotification('OffscreenCanvas Demo', {
body,
image,
tag: 'canvas',
});
}));
);