javascript - 创建 Github 徽章
问题描述
我想为 Github README 创建一个徽章(例如这样)。我创建了一个函数来使用 JavaScript 从 URL 获取 GET 值并将其放入 SVG 中,当我在本地尝试它时它可以工作,但如果我将它放入 Markdown 文件中它不会更改数字。
![No](http://luigitest.altervista.org/widget/font.svg?years=9)
索引.svg:
<svg width="200" height="75" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
style="-webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none;">
<g>
<rect x="0" y="0" width="125" height="75" style="fill:#F84949F5"></rect>
<text x="0" y="37.5" font-family="Segoe UI" font-size="16" font-weight="bold" fill="white">
<tspan x="62.5" text-anchor="middle" dy="-3.5%">I started</tspan>
<tspan x="62.5" text-anchor="middle" dy="25%">programming</tspan>
</text>
<rect x="124" y="0" width="75" height="75" style="fill:#F84949"></rect>
<text x="124" y="75" font-family="Segoe UI" font-size="13" fill="white" font-weight="bold">
<tspan x="162.5" text-anchor="middle" y="45.891675" font-size="40" id="years-number">5</tspan>
<tspan x="162.5" text-anchor="middle" y="67.5" font-weight="bold">years ago</tspan>
</text>
</g>
<script xlink:href="script.js" />
</svg>
脚本.js:
function changeNumber() {
document.getElementById("years-number").textContent = getValue;
}
let getValue;
window.addEventListener("load", function () {
let name="years";
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
getValue = decodeURIComponent(name[1]);
changeNumber();
});
浏览器中的输出: 正确的输出
markdown 中的输出(正确的一个): 输出错误
我该如何解决?
解决方案
您可以使用模板 svg 和 pupa 创建无服务器函数。
.svg 文件:
...svg
<tspan x="162.5" text-anchor="middle" y="45.891675" font-size="40" id="years-number">{years}</tspan>
...svg
服务器端代码:
// https://stackoverflow.com/questions/69164294/create-a-github-badge
import pupa from 'pupa'
import { readFileSync } from 'fs'
import { join } from 'path'
import { dirname } from 'dirname-filename-esm'
const __dirname = dirname(import.meta)
const template = readFileSync(join(__dirname, '../badge.svg'), 'utf8')
export default (req, res) => {
let { years } = req.query
if (typeof years !== 'string') return res.status(400).end()
res.setHeader('Content-Type', 'text/xml')
res.end(pupa(template, { years }))
}
我使用Vercel来部署无服务器功能。除了 Vercel,还有其他方法。
repl 链接:https ://replit.com/@Programmerraj/serverless-api#api/index.js
链接到实时示例:https ://serverless-api-ebon.vercel.app/api?years=6 (更改years
为任何内容)。
链接到 GitHub 存储库:https ://github.com/ChocolateLoverRaj/serverless-api 。
在此答案中以降价编写的预览:
推荐阅读
- java - 在 sbt 应用程序中自定义 ForkJoinPool
- c# - 升级到 ASP.NET Core 2.2 后如何配置 Azure 日志记录
- python - 在列表的字典中切换键和值
- c# - C#等待页面加载(网络浏览器)
- php - 将模型实例传递给另一个模型的函数
- google-cloud-platform - 将文件从 Linux 机器复制到 GCS 时出现异常
- visual-studio - 如何为 Visual Studio 2017 获取平台工具集“v90”?
- macos - 希望在不改变图像大小的情况下保存 NSImage
- angular - 角材料。移动设备屏幕外的对话框操作
- xcode - RCTFont.h 文件未找到