JavaScript canvas基于數(shù)組生成柱狀圖代碼實例
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í)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. XML在語音合成中的應(yīng)用2. HTTP協(xié)議常用的請求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))3. 不要在HTML中濫用div4. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)5. .NET Framework各版本(.NET2.0 3.0 3.5 4.0)區(qū)別6. jscript與vbscript 操作XML元素屬性的代碼7. HTML5實戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)8. php使用正則驗證密碼字段的復(fù)雜強度原理詳細講解 原創(chuàng)9. ASP基礎(chǔ)入門第四篇(腳本變量、函數(shù)、過程和條件語句)10. XML入門的常見問題(三)
