如何通过 map 函数为我在 p5.js 中创建的不同部分分配不同的颜色?

问题描述 投票:0回答:0

我应该如何为地图功能创建的每个部分分配不同的透明颜色?每个部分按比例代表美国政府在每个类别上的支出相对于其总支出的金额。我试过使用 setAlpha() 函数使颜色透明,但它产生了渐变而不是使其始终透明。不仅如此,我还在努力在不改变整个矩形的情况下对每个部分进行更改。

screenshot of current output

这是我现在的代码:

function setup() {
  createCanvas(800, 400);
  dollar=loadImage('https://media.istockphoto.com/id/1198332549/vector/american-usd-dollar-bill-outline-isolated-on-white-background.jpg?s=1024x1024&w=is&k=20&c=HLVlJ9Ak63IIK2ddS-I-_gr_rHKH8OEFlAGNVNMUhQw=')
  spending = [
    {name: "Social Security",
    billions: 1220},
    {name: "Health Care",
    billions: 914},
    {name: "Income Security",
    billions: 865},
    {name: "National Defense",
    billions: 767},
    {name: "Medicare",
    billions: 755},
    {name: "Education",
    billions: 677},
    {name: "Interest",
    billions: 475},
    {name: "Veteran Benefits",
    billions: 274},
    {name: "Transportation",
    billions: 132},
    {name: "Government",
    billions: 129},
    {name: "Other",
    billions: 65}
  ];
}

function draw() {
  background(255);
  image(dollar,80,-100)
  dollar.resize(600,0)
  for (let i=0;i<spending.length;i++){
    fill(255,0,0,10)
    let sectionwidth = map(spending[i].billions,0,6273,0,2470)
    rect(140,97,sectionwidth,205)
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>

我尝试设置 alpha 值,但这只会导致渐变。 我还尝试在我的条件语句中调整“i”的值,以便 p5.js 单独生成每个部分,但它会导致颜色从中间分开的矩形。

enter image description here

p5.js
© www.soinside.com 2019 - 2024. All rights reserved.