From 710d612ea5cfcd21fcddc0802843739463af1c2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=8F=B6?= <1936472877@qq.com> Date: Thu, 9 Jan 2025 19:08:36 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20canvas=E5=8A=A0=E8=BD=BD=E5=9B=BE?= =?UTF-8?q?=E7=89=87=E5=A2=9E=E5=8A=A0=E8=B6=85=E6=97=B6=E6=97=B6=E9=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- models/canvas/canvas.js | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/models/canvas/canvas.js b/models/canvas/canvas.js index d5d6a22..0792c1f 100644 --- a/models/canvas/canvas.js +++ b/models/canvas/canvas.js @@ -20,7 +20,29 @@ export const hasCanvas = !!canvasPKG const startTimeMap = new Map() -export const loadImage = hasCanvas && canvasPKG.loadImage +/** + * 加载图片 + * @param {any} source + * @param {import('@napi-rs/canvas').LoadImageOptions} options + * @returns {Promise} + */ +export const loadImage = async (source, options = {}) => { + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), 5000) + try { + const Image = await canvasPKG.loadImage(source, { + requestOptions: { + signal: controller.signal, + ...options.requestOptions + }, + ...options + }) + clearTimeout(timer) + return Image + } catch { + return null + } +} export function createCanvas (width, height) { if (!hasCanvas) throw new Error('请先pnpm i 安装依赖') @@ -63,7 +85,7 @@ export function toImage (canvas) { * @param {number} maxWidth * @param {string} replace */ -export function shortenText (ctx, text, maxWidth, replace = '...') { +export function shortenText (ctx, text, maxWidth, replace = '') { if (!text) return '' if (ctx.measureText(text).width <= maxWidth) return text while (ctx.measureText(text).width > maxWidth) {