JavaScript canvas基于數(shù)組生成柱狀圖代碼實(shí)例
HTML5 的 canvas 元素使用 JavaScript 在網(wǎng)頁(yè)上繪制圖像。
畫(huà)布是一個(gè)矩形區(qū)域,您可以控制其每一像素。
canvas 擁有多種繪制路徑、矩形、圓形、字符以及添加圖像的方法。
canvas 元素本身是沒(méi)有繪圖能力的。所有的繪制工作必須在 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; //每個(gè)柱狀圖的寬為總寬-間隙寬除個(gè)數(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; } }
效果:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Docker 容器健康檢查機(jī)制2. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫(huà)特效3. ASP.NET MVC使用正則表達(dá)式驗(yàn)證手機(jī)號(hào)碼4. PHP接收json并將接收數(shù)據(jù)插入數(shù)據(jù)庫(kù)5. python datetime時(shí)間格式的相互轉(zhuǎn)換問(wèn)題6. 基于python實(shí)現(xiàn)數(shù)組格式參數(shù)加密計(jì)算7. Rollup 簡(jiǎn)易入門(mén)示例教程8. Python requests庫(kù)參數(shù)提交的注意事項(xiàng)總結(jié)9. php判斷一個(gè)請(qǐng)求是ajax請(qǐng)求還是普通請(qǐng)求的方法10. python 爬取京東指定商品評(píng)論并進(jìn)行情感分析
