MCPcopy Create free account
hub / github.com/dailydotdev/apps / nodeToPng

Function nodeToPng

packages/shared/src/features/interests/nodeToPng.ts:28–71  ·  view source on GitHub ↗
(
  node: HTMLElement,
  scale = 2,
)

Source from the content-addressed store, hash-verified

26};
27
28export const nodeToPng = async (
29 node: HTMLElement,
30 scale = 2,
31): Promise<Blob> => {
32 const { width, height } = node.getBoundingClientRect();
33 const clone = node.cloneNode(true) as HTMLElement;
34
35 inline(node, clone);
36
37 // No parent lays the clone out, so it has to carry its on-screen box.
38 clone.style.margin = '0';
39 clone.style.width = `${width}px`;
40 clone.style.height = `${height}px`;
41
42 const markup = new XMLSerializer().serializeToString(clone);
43 const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><foreignObject x="0" y="0" width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml">${markup}</div></foreignObject></svg>`;
44
45 const image = new Image();
46 image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
47 await image.decode();
48
49 const canvas = document.createElement('canvas');
50 canvas.width = Math.round(width * scale);
51 canvas.height = Math.round(height * scale);
52
53 const ctx = canvas.getContext('2d');
54
55 if (!ctx) {
56 throw new Error('nodeToPng: rasterising needs a 2d context');
57 }
58
59 ctx.scale(scale, scale);
60 ctx.drawImage(image, 0, 0);
61
62 const blob = await new Promise<Blob | null>((done) =>
63 canvas.toBlob(done, 'image/png'),
64 );
65
66 if (!blob) {
67 throw new Error('nodeToPng: the canvas produced no image');
68 }
69
70 return blob;
71};

Callers 2

nodeToPng.spec.tsFile · 0.90
copyImageFunction · 0.90

Calls 1

inlineFunction · 0.85

Tested by

no test coverage detected