JavaScript canvas基于數(shù)組生成柱狀圖代碼實例
更新時間:2020年03月06日 08:48:50 作者:Island
這篇文章主要介紹了JavaScript canvas基于數(shù)組生成柱狀圖代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
HTML5 的 canvas 元素使用 JavaScript 在網(wǎng)頁上繪制圖像。
畫布是一個矩形區(qū)域,您可以控制其每一像素。
canvas 擁有多種繪制路徑、矩形、圓形、字符以及添加圖像的方法。
canvas 元素本身是沒有繪圖能力的。所有的繪制工作必須在 JavaScript 內(nèi)部完成:
canvas柱狀圖
var arr = [
{ id: 1001, price: 100 },
{ id: 1002, price: 150 },
{ id: 1003, price: 200 },
{ id: 1004, price: 70 },
{ id: 1005, price: 300 }
];
var gap = 20;
var canvas = document.querySelector("canvas");
var ctx;
init();
function init() {
canvas.width = 400;
canvas.height = 300;
ctx = canvas.getContext("2d");
var max = arr.reduce((value, item) => {
return value < item.price ? item.price : value;
}, arr[0].price);
//max高為300的4/5,其他的高為:300*(4/5)/(max) * h maxh:240 = othersh: ? ? = 240
var scaleHeight = 300 * 4 / 5 / max;
//每個柱狀圖的寬為總寬-間隙寬除個數(shù)
var width = (400 - (gap * (arr.length + 1))) / arr.length;
createChart(width, scaleHeight);
}
function createChart(w, hs) {
ctx.fillStyle = "rgba(0,0,0,0.7)";
ctx.fillRect(0, 0, 400, 300);
var x = 0;
for (var i = 0; i < arr.length; i++) {
x += gap;
ctx.fillStyle = "orange";
var h = hs * arr[i].price;
ctx.fillRect(x, 300 - h, w, h);
x += w;
}
}
效果:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Layui彈框中數(shù)據(jù)表格中可雙擊選擇一條數(shù)據(jù)的實現(xiàn)
這篇文章主要介紹了Layui彈框中數(shù)據(jù)表格中可雙擊選擇一條數(shù)據(jù)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
ionic cordova一次上傳多張圖片(類似input file提交表單)的實現(xiàn)方法
這篇文章主要介紹了ionic cordova一次上傳多張圖片(類似input file提交表單)的實現(xiàn)方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-12-12

