canvas系列教程03-柱狀圖項目1

弄了一堆線方塊和函數,感受挺玄乎,然並卵。咱們直接寫個項目看看。css

canvas一個比較拽的應用就是圖表和遊戲,咱們從淺入深,先玩圖表,圖表咱們今天說一個最簡單柱狀圖。
柱狀圖.pnghtml

柱狀圖不少人用百度的echars,那麼咱們會用更要會寫,爲啥?我見過太多的人問我echarts不可能徹底符合他們公司的需求,隨便改一點東西就不搞了,簡單的說咱們要作開發者,而不是一個js庫的搬運工,咱們今天就參考這個效果http://echarts.baidu.com/demo...,寫一個。canvas

無話可說先搭架子。echarts

index.htmldom

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>尼古拉斯·屌·大彬哥</title>
  <link rel="stylesheet" href="style.css" rel="stylesheet">
  <script src="index.js"></script>
</head>
<body>
  <div id="div1">
    這裏留着畫圖用
  </div>
</body>
</html>

index.js函數

'use strict';
//模仿 http://echarts.baidu.com/demo.html#bar-gradient
window.onload = function(){
    var data = [
      {"label":"一月","value":getRandomInt(0,400)},
      {"label":"一月","value":getRandomInt(1,400)},
      {"label":"一月","value":getRandomInt(1,400)}
    ];

    var targetId = 'bchart';
    var cw = 800;
    var ch = 600;

    function Bcharts(targetId,cw,ch,data){
        console.log(arguments);
    }

    var charts = new Bcharts(targetId,cw,ch,data);
};
//https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math/random
// 偷個懶,基礎函數不寫了
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}

style.cssui

#div1{
  width:800px;
  height:600px;
  border: 1px solid #000;
  margin: 0 auto;
}

說三件事,spa

第一件事,搭好架子,後面寫代碼舒服。這裏用的面向對象方式。code

第二件事,基礎的函數我就不寫了,可是你寫過100遍以上徹底懂能夠偷懶,不然老老實實本身研究明白他。htm

第三件事,數據我用的data模擬,實際項目通常是後臺提供。

相關文章
相關標籤/搜索