求助:Google Charts饼图如何实现真正的随机颜色
Hey there! I see you're stuck trying to get fully random colors for your Google Charts Pie Chart—let's figure this out together.
Why Your Current Code Isn't Working
The key issue here is that when you define a colors array in your options, Google Charts completely ignores the useRandomColors: true setting. It prioritizes your predefined color list first, which is why your pie slices keep following the yellow → red → blue order you set.
Solution: Generate Custom Random Colors
Instead of relying on the (somewhat limited) useRandomColors flag, we can build a simple function to generate totally random hex colors, then dynamically populate the colors option with these values. Here's your updated code:
<head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); // Helper function to create a random hex color function getRandomColor() { const hexChars = '0123456789ABCDEF'; let color = '#'; for (let i = 0; i < 6; i++) { color += hexChars[Math.floor(Math.random() * 16)]; } return color; } function drawChart() { var data = google.visualization.arrayToDataTable([ ['Task', 'Hours per Day'], ['Work', 2], ['Eat', 4], ['Commute', 5], ['Watch TV', 8], ['Sleep', 9], ]); // Generate enough random colors for each data entry const colorCount = data.getNumberOfRows(); const randomColors = []; for (let i = 0; i < colorCount; i++) { randomColors.push(getRandomColor()); } var options = { title: 'Test', colors: randomColors, // Use our dynamically generated random colors }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script> </head> <body> <div id="piechart" style="width: 900px; height: 500px;"></div> </body>
How This Works
- The
getRandomColor()function creates a unique 6-character hex color (like#2D78B3or#F9C80E) every time it's called. - We count how many data rows you have (excluding the header) using
data.getNumberOfRows(). - We loop that number of times to generate a matching set of random colors, then assign this array to the
colorsoption.
Now every time you refresh the page, your pie chart will have a brand new set of totally random colors—no fixed list holding you back!
If you want to avoid overly similar colors (e.g., too many dark or light shades), you could tweak the getRandomColor() function to restrict values for brighter/darker hues, but this basic version should perfectly meet your "fully random" requirement.
内容的提问来源于stack exchange,提问作者Nina

