import { domToCanvas } from 'modern-screenshot' import { API_BASE_URL } from '../api/setup' const W = 1080 const SIDE = 60 // 시간대별 배경 (화면 하늘 배경과 같은 색) const SKY: Record = { morning: ['#ffe0c4', '#fff0e2', '#e4f2ff'], day: ['#cde7ff', '#e9f5ff', '#f7fbff'], sunset: ['#ffd0b5', '#f9c3cf', '#ddd2f6'], night: ['#0e1433', '#1b2356', '#2a2e6e'], } /** 공유 이미지 크기. 위: 로고·지역 날짜, 가운데: 카드, 아래: 주소 */ export const SHARE_SIZES = { story: { ratio: '9:16', w: 9, hr: 16, h: 1920, logoY: 250, logoPx: 96, subY: 325, subPx: 40, pillY: 1760, pillH: 100, labelPx: 34, hostPx: 46 }, feed: { ratio: '4:5', w: 4, hr: 5, h: 1350, logoY: 140, logoPx: 76, subY: 200, subPx: 34, pillY: 1250, pillH: 84, labelPx: 30, hostPx: 40 }, square: { ratio: '1:1', w: 1, hr: 1, h: 1080, logoY: 115, logoPx: 64, subY: 168, subPx: 30, pillY: 990, pillH: 80, labelPx: 28, hostPx: 38 }, } as const export type ShareSize = keyof typeof SHARE_SIZES const LOGO = (px: number) => `${px}px Jua, sans-serif` const SANS = (px: number) => `bold ${px}px "Pretendard Variable", sans-serif` const PILL_LABEL = '오늘 내 동네 각 보기' // 버튼·조작 표시(data-noshot)는 이미지에 넣지 않는다. 링크(장소 등)는 글자라 남긴다 const keep = (n: Node) => !(n instanceof HTMLButtonElement || (n instanceof HTMLElement && n.dataset.noshot != null)) function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) { ctx.beginPath() ctx.roundRect(x, y, w, h, r) } const URL_RE = /url\((['"]?)([^'")]+)\1\)/g const dataUrls = new Map>() function dataUrl(url: string): Promise { let p = dataUrls.get(url) if (!p) { p = fetch(url) .then((r) => { if (!r.ok) throw new Error(`font ${r.status} ${url}`) return r.blob() }) .then((b) => new Promise((resolve, reject) => { const fr = new FileReader() fr.onload = () => resolve(fr.result as string) fr.onerror = () => reject(fr.error) fr.readAsDataURL(b) })) p.catch(() => dataUrls.delete(url)) dataUrls.set(url, p) } return p } // "U+AC00-AC5F, U+4??" 가 text 의 글자를 하나라도 덮는지 function covers(range: string, codes: number[]) { if (!range) return true return range.split(',').some((part) => { const [a, b] = part.trim().replace(/^u\+/i, '').split('-') const lo = parseInt(a.replace(/\?/g, '0'), 16) const hi = parseInt((b ?? a).replace(/\?/g, 'f'), 16) return codes.some((c) => c >= lo && c <= hi) }) } /** * 카드 글자에 필요한 웹폰트 조각만 data URL 로 넣은 @font-face. * 이미지는 SVG 로 그려져 문서 폰트를 못 쓰므로 직접 넣어야 글꼴이 안 깨진다 (한글 폰트는 조각 수백 개라 전부 넣지 않는다). */ async function fontCss(text: string): Promise { const codes = [...new Set(Array.from(text, (ch) => ch.codePointAt(0) ?? 0))] const rules: { css: string; base: string }[] = [] for (const sheet of Array.from(document.styleSheets)) { let list: CSSRuleList try { list = sheet.cssRules } catch (e) { console.warn('[share] font css unreadable', sheet.href, e) continue } for (const r of Array.from(list)) { if (r instanceof CSSFontFaceRule && covers(r.style.getPropertyValue('unicode-range'), codes)) rules.push({ css: r.cssText, base: sheet.href ?? location.href }) } } const out = await Promise.all( rules.map(async ({ css, base }) => { const urls = [...css.matchAll(URL_RE)].map((m) => m[2]) const data = await Promise.all(urls.map((u) => dataUrl(new URL(u, base).href))) let i = 0 return css.replace(URL_RE, () => `url("${data[i++]}")`) }), ) return out.join('\n') } // 다른 사이트 사진은 브라우저가 픽셀을 못 읽는 경우가 있어 백엔드가 대신 받아 준다. 허용 여부는 백엔드(IMAGE_PROXY_HOSTS)가 정한다 function viaProxy(url: string): Promise { if (!URL.canParse(url)) return Promise.resolve(false) const u = new URL(url) if (u.origin === location.origin || !u.protocol.startsWith('http')) return Promise.resolve(false) return dataUrl(`${API_BASE_URL}/v1/image?url=${encodeURIComponent(url)}`).catch((e: unknown) => { console.warn('[share] image proxy', url, e) return false as const }) } type Box = { x: number; y: number; w: number; h: number } // 카드 자리. 2장이면 세로 이미지는 지그재그, 나머지는 나란히(오른쪽을 조금 내려) 놓는다 function place(n: number, aspect: number, top: number, bottom: number): Box[] { const room = bottom - top if (n === 1) { const w = Math.min(W - SIDE * 3, room / aspect) const h = w * aspect return [{ x: (W - w) / 2, y: top + (room - h) / 2, w, h }] } if (room / W > 1.1) { const h = Math.min(room / 2, ((W - SIDE * 2) * 0.52) * aspect) const w = h / aspect const y = top + (room - h * 2) / 2 return [{ x: SIDE, y, w, h }, { x: W - SIDE - w, y: y + h, w, h }] } const gap = 40 const w = Math.min((W - SIDE * 2 - gap) / 2, room / aspect / 1.08) const h = w * aspect const y = top + (room - h * 1.08) / 2 return [{ x: W / 2 - gap / 2 - w, y, w, h }, { x: W / 2 + gap / 2, y: y + h * 0.08, w, h }] } function badge(ctx: CanvasRenderingContext2D, x: number, y: number, n: number) { ctx.beginPath() ctx.arc(x, y, 30, 0, Math.PI * 2) ctx.fillStyle = '#ff7a45' ctx.fill() ctx.fillStyle = '#fff' ctx.font = LOGO(36) ctx.textBaseline = 'middle' ctx.fillText(String(n), x, y + 2) ctx.textBaseline = 'alphabetic' } /** 게시물 슬라이드(최대 2장)를 고른 크기의 PNG 한 장으로 만든다 */ export async function shareImage(slides: HTMLElement[], opts: { size: ShareSize; sky: string; sub: string; host: string }): Promise { const z = SHARE_SIZES[opts.size] const cards = slides.slice(0, 2) if (!cards.length) throw new Error('no slide to capture') await Promise.all([ document.fonts.load(LOGO(z.logoPx), '날씨각'), document.fonts.load(LOGO(z.hostPx), opts.host), document.fonts.load(LOGO(36), '12'), document.fonts.load(SANS(z.subPx), opts.sub), document.fonts.load(SANS(z.labelPx), PILL_LABEL), ]) const css = await fontCss(cards.map((c) => c.textContent ?? '').join('')) const aspect = cards[0].offsetHeight / cards[0].offsetWidth const boxes = place(cards.length, aspect, z.subY + 60, z.pillY - z.pillH / 2 - 50) const shots = await Promise.all(cards.map((c, i) => domToCanvas(c, { scale: boxes[i].w / c.offsetWidth, filter: keep, font: css ? { cssText: css } : false, fetchFn: viaProxy }))) const canvas = document.createElement('canvas') canvas.width = W canvas.height = z.h const ctx = canvas.getContext('2d') if (!ctx) throw new Error('canvas 2d context unavailable') const dark = opts.sky === 'night' const [c1, c2, c3] = SKY[opts.sky] ?? SKY.day const bg = ctx.createLinearGradient(0, 0, 0, z.h) bg.addColorStop(0, c1) bg.addColorStop(0.45, c2) bg.addColorStop(1, c3) ctx.fillStyle = bg ctx.fillRect(0, 0, W, z.h) ctx.textAlign = 'center' ctx.fillStyle = '#ff7a45' ctx.font = LOGO(z.logoPx) ctx.fillText('날씨각', W / 2, z.logoY) ctx.fillStyle = dark ? '#bcc3ea' : '#5a6380' ctx.font = SANS(z.subPx) ctx.fillText(opts.sub, W / 2, z.subY, W - SIDE * 2) const r = 40 * (boxes[0].w / 900) shots.forEach((shot, i) => { const b = boxes[i] ctx.save() ctx.shadowColor = 'rgb(40 48 74 / 0.25)' ctx.shadowBlur = 50 ctx.shadowOffsetY = 20 roundRect(ctx, b.x, b.y, b.w, b.h, r) ctx.fillStyle = '#fff' ctx.fill() ctx.restore() ctx.save() roundRect(ctx, b.x, b.y, b.w, b.h, r) ctx.clip() ctx.drawImage(shot, b.x, b.y, b.w, b.h) ctx.restore() }) if (shots.length > 1) boxes.forEach((b, i) => badge(ctx, b.x + 6, b.y + 6, i + 1)) // 주소 알약: [오늘 내 동네 각 보기 host] ctx.font = SANS(z.labelPx) const lw = ctx.measureText(PILL_LABEL).width ctx.font = LOGO(z.hostPx) const hw = ctx.measureText(opts.host).width const gap = 20 const pw = Math.min(W - SIDE * 2, lw + gap + hw + 96) const px = (W - pw) / 2 ctx.save() ctx.shadowColor = 'rgb(40 48 74 / 0.14)' ctx.shadowBlur = 30 ctx.shadowOffsetY = 10 roundRect(ctx, px, z.pillY - z.pillH / 2, pw, z.pillH, z.pillH / 2) ctx.fillStyle = '#fff' ctx.fill() ctx.restore() ctx.textAlign = 'left' ctx.textBaseline = 'middle' ctx.fillStyle = '#5a6380' ctx.font = SANS(z.labelPx) ctx.fillText(PILL_LABEL, px + 48, z.pillY + 2) ctx.fillStyle = '#ff7a45' ctx.font = LOGO(z.hostPx) ctx.fillText(opts.host, px + 48 + lw + gap, z.pillY + 4, pw - 96 - lw - gap) return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/png')) }