I'm trying to create a word-cloud with font-size based on percent of total. Each word has a "count" attribute.
<h2>Cryptos</h2>
<div class="topics">
{#each cryptos as topic}
<a
href="/cryptos/{topic._id}"
style="font-size: {(topic.count / topics[0].count) * 100 + 100}%;">${topic._id}
({topic.count})</a>
{/each}
</div>
This isn't quite working correctly and I'm not sure why.
font-size: {(topic.count / topics[0].count) * 100 + 100}%;
The topics are sorted in descending order based on .count
I basically want the font-size to be 100% at the low end and 200% at the high end.
The font size can be varied by comparing the range of font sizes with the range of word counts.
Imagine you have a list of words and their count:
const words = [
{ text: "apples", count: 10 },
{ text: "pears", count: 30 },
// ...
]
The range of font-size
can be computed:
const minFontSize = 10
const maxFontSize = 30
// delta between sizes
const fontRange = maxFontSize - minFontSize
Then compute the min word count, max word count and the range of word count. Reactive statements work well for this:
// list of counts
$: counts = words.map(record => record.count)
// minimum word count
$: min = Math.min(...counts)
// maximum word count
$: max = Math.max(...counts)
// delta between smallest and largest word count
$: countRange = max - min
Now we can compute the font size:
minFontSize + (deltaWordCount * sizeRatio)
or more specifically:
{#each words as word}
<span style="font-size: {minFontSize + ((word.count - min) * (fontRange / countRange))}px">
{word.text}
</span>
{/each}
You can find a working example here: https://svelte.dev/repl/770e4a35186449a182b8edecc4ed88ba?version=3.31.0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.