[英]How to calculate relative percent to total?
我正在尝试根据总数的百分比创建一个字体大小的词云。 每个单词都有一个“计数”属性。
<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>
这不太正常,我不知道为什么。
font-size: {(topic.count / topics[0].count) * 100 + 100}%;
主题按.count
降序排列
我基本上希望字体大小在低端为 100%,在高端为 200%。
通过比较字体大小的范围和字数的范围,可以改变字体大小。
想象一下,您有一个单词列表及其计数:
const words = [
{ text: "apples", count: 10 },
{ text: "pears", count: 30 },
// ...
]
可以计算font-size
的范围:
const minFontSize = 10
const maxFontSize = 30
// delta between sizes
const fontRange = maxFontSize - minFontSize
然后计算最小字数、最大字数和字数范围。 反应式语句适用于此:
// 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
现在我们可以计算字体大小:
minFontSize + (deltaWordCount * sizeRatio)
或更具体地说:
{#each words as word}
<span style="font-size: {minFontSize + ((word.count - min) * (fontRange / countRange))}px">
{word.text}
</span>
{/each}
您可以在这里找到一个工作示例: https://svelte.dev/repl/770e4a35186449a182b8edecc4ed88ba?version=3.31.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.