50 lines
1.8 KiB
JavaScript
50 lines
1.8 KiB
JavaScript
// Node 里用 require,插件页面里用 <script> 标签挂到 window。
|
||
(function () {
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
|
||
// 插件根目录必须延迟计算:Eagle 在 onPluginCreate 里才给出 plugin.path,
|
||
// 那时代码已经加载完了,所以这里用函数而不是常量。
|
||
function pluginRootPath() {
|
||
if (typeof window !== 'undefined') {
|
||
const fromEagle = window.SpinePluginPath || window.SpinePluginRoot;
|
||
if (fromEagle) return fromEagle;
|
||
}
|
||
return typeof __dirname !== 'undefined' ? path.join(__dirname, '..') : '.';
|
||
}
|
||
|
||
function badgeFile() {
|
||
return path.join(pluginRootPath(), 'assets', 'spine-badge.png');
|
||
}
|
||
let cachedDataUrl = null;
|
||
|
||
function dataUrl() {
|
||
if (!cachedDataUrl) {
|
||
cachedDataUrl = 'data:image/png;base64,' + fs.readFileSync(badgeFile()).toString('base64');
|
||
}
|
||
return cachedDataUrl;
|
||
}
|
||
|
||
function drawVersion(ctx, width, height, version) {
|
||
version = String(version || '');
|
||
if (version.length > 40 || !/^\d+\.\d+(?:\.\d+)?(?:[-+][a-z0-9][a-z0-9.-]*)?$/i.test(version)) return;
|
||
const fontSize = Math.max(12, Math.round(Math.min(width, height) * 0.055));
|
||
const margin = Math.max(10, Math.round(Math.min(width, height) * 0.03));
|
||
ctx.save();
|
||
try {
|
||
ctx.font = '600 ' + fontSize + 'px sans-serif';
|
||
ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
|
||
const boxHeight = fontSize + 12;
|
||
const y = height - margin - boxHeight;
|
||
ctx.fillStyle = 'rgba(0,0,0,0.65)';
|
||
ctx.fillRect(margin, y, ctx.measureText(version).width + 16, boxHeight);
|
||
ctx.fillStyle = '#ffffff'; ctx.fillText(version, margin + 8, y + boxHeight / 2);
|
||
} finally { ctx.restore(); }
|
||
}
|
||
|
||
const api = { get path() { return badgeFile(); }, dataUrl, drawVersion };
|
||
if (typeof window !== 'undefined') window.SpineBadge = api;
|
||
else if (typeof module !== 'undefined' && module.exports) module.exports = api;
|
||
|
||
})();
|