1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
export async function getChartImage( charts, outCanvasId, drawHorizontal = false ) { if (!Array.isArray(charts) || charts.length === 0 || !outCanvasId) return {}; const arr = charts.map(item => { if ("toDataURL" in item) { return { base64Str: item.toDataURL("image/jpeg"), width: item.width, height: item.height, }; } return item; }); const offsetY = 30; const offsetX = 20;
const width = drawHorizontal ? arr.reduce((res, cur) => { return res + cur.width; }, (arr.length - 1) * offsetX) : Math.max(...arr.map(v => v.width)); const height = drawHorizontal ? Math.max(...arr.map(v => v.height)) : arr.reduce((res, cur) => { return res + cur.height; }, (arr.length - 1) * offsetY);
const imgs = await Promise.all( arr.map(v => { return new Promise(res => { const img = new Image(); img.src = v.base64Str; img.addEventListener("load", () => { res(img); }); }); }) );
const canvas = document.getElementById(outCanvasId); const context = canvas.getContext("2d");
canvas.width = width; canvas.height = height;
context.fillStyle = "#fff"; context.fillRect(0, 0, width, height); imgs.forEach((img, index) => { const idx = index && index - 1; if (drawHorizontal) { context.drawImage(img, index * (imgs[idx].width + offsetX), 0); } else { context.drawImage(img, 0, index * (imgs[idx].height + offsetY)); } });
const newBase64 = canvas.toDataURL("image/jpeg", 0.9); return { base64Str: newBase64, width, height, }; }
|