/* 描摹前处理与 SVG 输出工具(与引擎无关的纯工具函数)。
*
* 上一版(VTracer)里的降噪、背景层剔除、viewBox 修补在这里**全部删掉**了:
* - 降噪:potrace 的 turdSize 天生去小点,不需要先降采样糊一遍;
* - 背景层剔除:potrace 按明暗分层,白底自然成为最亮的一层,不再需要删 path;
* - viewBox 修补:potrace 自己就输出 width/height/viewBox(实测),不用二次拼接。
* 留下的只有:读图 → 必要时降采样 → 生成 PNG / 统计。
*/
'use strict'
import { MAX_TRACE_SIDE } from './engine.js'
/** 读 data URL 成
(走浏览器解码,与画布语义一致) */
export function loadImage(dataUrl) {
return new Promise(function (resolve, reject) {
const img = new Image()
img.onload = function () { resolve(img) }
img.onerror = function () { reject(new Error('图片解码失败')) }
img.src = dataUrl
})
}
/**
* 准备描摹用的像素:potrace 是单线程纯 JS,超过 MAX_TRACE_SIDE 会明显卡主线程,
* 所以先按长边夹取(**只缩不放**)。
* @returns {{canvas:HTMLCanvasElement, w:number, h:number, srcW:number, srcH:number, clamped:boolean}}
*/
export function prepareSource(img) {
const srcW = img.naturalWidth || img.width
const srcH = img.naturalHeight || img.height
const longSide = Math.max(srcW, srcH)
const k = longSide > MAX_TRACE_SIDE ? MAX_TRACE_SIDE / longSide : 1
const w = Math.max(1, Math.round(srcW * k))
const h = Math.max(1, Math.round(srcH * k))
const canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
const ctx = canvas.getContext('2d', { willReadFrequently: true })
ctx.imageSmoothingEnabled = true
ctx.drawImage(img, 0, 0, w, h)
return { canvas, w, h, srcW, srcH, clamped: k < 1 }
}
/** SVG 字符串 →
(导出时把矢量光栅化) */
export function svgToImage(svg) {
return new Promise(function (resolve, reject) {
const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' })
const url = URL.createObjectURL(blob)
const img = new Image()
img.onload = function () { URL.revokeObjectURL(url); resolve(img) }
img.onerror = function () { URL.revokeObjectURL(url); reject(new Error('矢量渲染失败')) }
img.src = url
})
}
/**
* 把矢量结果光栅化成 PNG(保存为节点用)。outScale 只影响像素尺寸 ——
* 曲线按 viewBox 缩放渲染,所以 2× 是真的更清晰,不是插值放大。
*/
export async function svgToPngBlob(svg, baseW, baseH, outScale) {
const img = await svgToImage(svg)
const k = Math.max(1, Math.min(4, Number(outScale) || 1))
const w = Math.max(1, Math.round(baseW * k))
const h = Math.max(1, Math.round(baseH * k))
const canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, w, h)
return new Promise(function (resolve, reject) {
canvas.toBlob(function (blob) {
if (blob) resolve(blob)
else reject(new Error('PNG 编码失败'))
}, 'image/png')
})
}
/** 统计:路径数、填充色数、字节数(面板上「体积」那个数字) */
export function svgStats(svg) {
const text = String(svg)
const paths = (text.match(/