直書きSVGをダウンロードする
scrapboxで
htmlに直書きのsvgをワンタップで画像としてダウンロードしたい
これらを実現するためにsvgをbolbで置き換えることを検討したが,どうだろうか
なるべくブラウザ標準の機能を使うために
こういう既成の拡張機能はあるか?
svgが更新された時,bolbも更新しないと
直書きsvgを全てダウンロードするJSを書いて
複数のSVGが取得される可能性もあるので,実行すると,SVG一覧が別タブで開いてそれをクリックしてダウンロードできるようなスクリプトを書いて
code:.js
(() => {
function main() {
const svgs = document.querySelectorAll('svg');
if (svgs.length === 0) {
console.warn('SVGが見つかりませんでした');
return;
}
// SVG一覧HTMLを生成
const items = Array.from(svgs).map((svg, index) => {
const svgString = new XMLSerializer().serializeToString(svg);
const blob = new Blob(svgString, { type: 'image/svg+xml' }); const blobURL = URL.createObjectURL(blob);
const width = svg.clientWidth || 200;
const height = svg.clientHeight || 200;
return `
<div class="item">
<div class="preview">
<img src="${blobURL}" width="${width}" height="${height}" />
</div>
<a href="${blobURL}" download="svg_${index + 1}.svg" class="btn">
⬇ svg_${index + 1}.svg をダウンロード
</a>
</div>`;
}).join('');
const html = `<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>SVG一覧 (${svgs.length}件)</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: sans-serif;
padding: 24px;
}
h1 {
font-size: 20px;
margin-bottom: 20px;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 16px;
}
.item {
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
padding: 16px;
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
}
.preview {
width: 100%;
display: flex;
justify-content: center;
align-items: center;
border-radius: 4px;
min-height: 120px;
overflow: hidden;
}
.preview img {
max-width: 100%;
max-height: 200px;
object-fit: contain;
}
.btn {
display: inline-block;
padding: 8px 16px;
text-decoration: none;
border-radius: 4px;
font-size: 13px;
transition: background 0.2s;
}
.download-all {
margin-bottom: 20px;
padding: 10px 20px;
border: none;
border-radius: 4px;
font-size: 14px;
cursor: pointer;
}
.download-all:hover { background: #1e8449; } </style>
</head>
<body>
<h1>SVG一覧(${svgs.length}件)</h1>
<div class="grid">${items}</div>
</body>
</html>`;
const pageBlob = new Blob(html, { type: 'text/html' }); const pageURL = URL.createObjectURL(pageBlob);
window.open(pageURL, '_blank');
}
main();
})();