普段使いアイコン画像の生成方法のメモ書き

/
#memo

はじめに

この投稿は自分用のメモ書きなので、参考を利用することで説明をできるだけ省き、保存しておきたいコードなどをメモ書きすることに徹する。

普段使っているアイコン画像

Easing Gradients などの CSS ジェネレータで好きな色や形の CSS を取得し、HTML に反映させて、それを画像変換ライブラリなどを使って生成している。基本的に青系統の色が好き。ヱヴァンゲリヲン新劇場版:Q や初音ミクもこんな色。Top | Kawano Yudai では --color-miku: #00e1ee; と CSS 変数を設定している。何色なのかわからないので、取り敢えず近い色を使用している初音ミクの名前を借りた。

HTML と CSS

undefined
1
<div class='border forNow' />
gradient.css
1
#target {
2
display: inline-block;
3
padding: 50px;
4
opacity: .9;
5
}
6
7
.border {
8
width: 300px;
9
height: 300px;
10
border-radius: 30% 70% 59% 41% / 30% 26% 74% 70%;
11
}
12
13
.forNow {
14
background: linear-gradient(to top right,
15
hsl(157.83, 100%, 45.1%) 0%,
16
hsl(158.37, 100%, 44.88%) 9.1%,
17
hsl(159.93, 100%, 44.27%) 16.8%,
18
hsl(162.39, 100%, 43.3%) 23.5%,
19
hsl(165.67, 100%, 42.03%) 29.2%,
20
hsl(169.74, 100%, 40.48%) 34.4%,
21
hsl(174.6, 100%, 38.69%) 39.1%,
22
hsl(180.28, 100%, 36.88%) 43.6%,
23
hsl(186.13, 100%, 38.5%) 48.2%,
24
hsl(191.54, 100%, 40.03%) 53%,
25
hsl(196.45, 100%, 41.43%) 58.3%,
26
hsl(200.81, 100%, 42.65%) 64.3%,
27
hsl(204.51, 100%, 43.66%) 71.3%,
28
hsl(207.41, 100%, 44.43%) 79.4%,
29
hsl(209.31, 100%, 44.92%) 88.9%,
30
hsl(210, 100%, 45.1%) 100%);
31
}

PNG や SVG として取得

今までは画像化ライブラリに tsayen/dom-to-image を使っていたが、当投稿中に bubkoo/html-to-image を見つけたのでこちらを使う。

undefined
1
npm create vite@latest gradient -- --template react-ts
2
npm i html-to-image
App.tsx
1
import React, { useCallback, useRef } from 'react'
2
import { toSvg } from 'html-to-image';
3
4
import "./gradient.css"
5
6
const App: React.FC = () => {
7
const ref = useRef<HTMLDivElement>(null)
8
9
function filter(node: any) {
10
return (node.tagName !== 'i');
11
}
12
13
const handleClick = useCallback(() => {
14
if (ref.current === null) return;
15
16
toSvg(ref.current, { filter })
17
.then((dataUrl) => {
18
const link = document.createElement('a')
19
link.download = 'gradient.svg'
20
link.href = dataUrl
21
link.click()
22
})
23
.catch((err) => {
24
console.log(err)
25
})
26
}, [ref])
27
28
return (
29
<>
30
<button onClick={handleClick}>Click me</button>
31
<div id='target' ref={ref}>
32
<div className='border forNow' />
33
</div>
34
<div id='dest'></div>
35
</>
36
)
37
}
38
39
export default App

toPng を使うと、下の画像が得られる。

gradient icon image

今まで書いてたコード

※だいぶ前に書いたもの。

App.tsx
1
import React from 'react'
2
import domtoimage from 'dom-to-image'
3
4
const App: React.VFC = () => {
5
const onClick = async (e: any) => {
6
e.preventDefault()
7
const node = currentTarget
8
const dest = document.getElementById('dest')
9
10
try {
11
const img = new Image()
12
img.src = await domtoimage.toPng(node)
13
dest?.appendChild(img)
14
} catch (error) {
15
console.log(error)
16
}
17
}
18
19
return (
20
<>
21
<div id='target' onClick={onClick}>
22
<div className='border forNow' />
23
</div>
24
<div id='dest'></div>
25
</>
26
)
27
}
28
29
export default App;

参照