我正在嘗試使用純 JS 創建資料可視化。我找不到任何不依賴第三方庫的示例來說明如何執行此操作。
假設您有一些資料:
data = {
green = 20%;
yellow = 30%;
red = 50%;
}
您已經在 HTML 中創建了一個可以填充顏色的矩形。
如何使用JS根據每種顏色的百分比填充顏色?正如您將在下面的代碼中看到的,現在我只是在顏色百分比中進行了硬編碼。但我希望它是動態的,以便在資料更改時更新。
這是我到目前為止所擁有的:
const drawColors = () => {
const colorBar = document.getElementById("color-bar");
const context = colorBar.getContext('2d');
// Hard coding percentages
context.beginPath();
context.fillStyle = "green";
context.fillRect(0, 0, 100, 100);
context.fillStyle = "yellow"
context.fillRect(100, 0, 100, 100);
context.fillStyle = "red"
context.fillRect(200, 0, 100, 100);
}
drawColors();
<canvas id="color-bar" width="300" height="100">
uj5u.com熱心網友回復:
假設您在其他地方驗證百分比值的總和為 100,請遍歷百分比物件并像這樣填充:
const percentages = {
green: 50,
yellow: 30,
red: 20
}
const drawColors = () => {
const colorBar = document.getElementById("color-bar")
const context = colorBar.getContext('2d')
//Calculate pixels from percentage based on canvas width.
const toPixels = percentage => (percentage*colorBar.width)/100
context.beginPath()
let addedColors = 0 //To set the starting point of each fill.
Object.keys(percentages).forEach(color => {
let widthToPaint = toPixels(percentages[color])
context.fillStyle = color
context.fillRect(addedColors, 0, widthToPaint , 100)
addedColors = widthToPaint
})
}
drawColors()
<canvas id="color-bar" width="300" height="100">
uj5u.com熱心網友回復:
我們可以createLinearGradient()為此使用。剛剛將 20% 轉換為 0.2 等(總和必須為 1 或更少);
data = {
green : 0.2,
yellow : 0.3,
red : 0.5
}
drawColorBar('canvas',data);
function drawColorBar(selector, data){
const canvas = document.querySelector(selector);
const ctx = canvas.getContext('2d');
const gradient = ctx.createLinearGradient(0,0,canvas.width,0);
let start = 0;
for(const color in data){
gradient.addColorStop(start, color);
start = data[color];
gradient.addColorStop(start, color);
}
ctx.fillStyle = gradient;
ctx.fillRect(0,0,canvas.width,canvas.height);
}
<canvas></canvas>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/350022.html
