UNPKG

@antv/s2

Version:

effective spreadsheet render core lib

124 lines 4.34 kB
import { __awaiter } from "tslib"; const loadError = new Error('Failed to load image and fallback'); export function asyncDrawImage(options) { const { src, fallback, timeout = 10000, mediaCache, crossOrigin = 'Anonymous', cacheKeyPrefix, } = options; const cacheKey = cacheKeyPrefix ? `${cacheKeyPrefix}:${src}` : src; return new Promise((resolve, reject) => { if (mediaCache === null || mediaCache === void 0 ? void 0 : mediaCache.has(cacheKey)) { const cacheImg = mediaCache.get(cacheKey); if (cacheImg instanceof HTMLImageElement) { resolve(cacheImg); return; } if (cacheImg === null) { reject(loadError); return; } } const cacheResolve = (img) => { mediaCache === null || mediaCache === void 0 ? void 0 : mediaCache.set(cacheKey, img); resolve(img); }; const cacheReject = (error) => { mediaCache === null || mediaCache === void 0 ? void 0 : mediaCache.set(cacheKey, null); reject(error); }; const processFallback = () => { if (fallback) { // fallback 图片使用原始URL作为缓存key(不带前缀),避免污染主缓存 asyncDrawImage({ src: fallback, timeout, mediaCache, }) .then(cacheResolve) .catch(cacheReject); } else { // 如果没有 fallback 或者 fallback 也失败,返回错误 cacheReject(loadError); } }; const onerror = () => { if (crossOrigin) { // 第二次加载不再使用跨域请求,但会因浏览器安全策略导致Canvas的toDataUrl失败(不推荐) asyncDrawImage({ src, timeout, mediaCache, crossOrigin: null, cacheKeyPrefix, }) .then(cacheResolve) .catch(processFallback); } else { processFallback(); } }; const img = new Image(); img.src = src; img.crossOrigin = crossOrigin; // 设置超时 const timeoutId = setTimeout(onerror, timeout); img.onload = () => { clearTimeout(timeoutId); cacheResolve(img); }; img.onerror = () => { clearTimeout(timeoutId); onerror(); }; img.onabort = () => { clearTimeout(timeoutId); onerror(); }; }); } /** * 计算图片最佳缩放尺寸 * @param {number} containerWidth 容器宽度 * @param {number} containerHeight 容器高度 * @param {number} naturalWidth 图片原始宽度 * @param {number} naturalHeight 图片原始高度 * @returns {{ width: number, height: number }} */ export function calculateImageSize(containerWidth, containerHeight, naturalWidth, naturalHeight) { if (containerWidth <= 0 || containerHeight <= 0) { return { width: 0, height: 0, }; } if (naturalWidth <= 0 || naturalHeight <= 0) { return { width: containerWidth, height: containerHeight, }; } // 计算宽高比例限制 const widthRatio = containerWidth / naturalWidth; const heightRatio = containerHeight / naturalHeight; // 取最小值防止溢出 const scale = Math.min(widthRatio, heightRatio); // 返回整数尺寸 (避免亚像素模糊) return { width: Math.floor(naturalWidth * scale), height: Math.floor(naturalHeight * scale), }; } export function getPreparedText(prepareText_1) { return __awaiter(this, arguments, void 0, function* (prepareText, text = '') { try { if (prepareText) { text = (yield prepareText(text)) || text; } } catch (e) { // eslint-disable-next-line no-console console.warn(`fail to prepareText`, e); } return text; }); } //# sourceMappingURL=customRenderer.js.map