首页 > 代码库 > canvas - 柱子效果

canvas - 柱子效果

技术分享

 

<!DOCTYPE html>  
<html>  
<head>  
<meta charset="utf-8">  
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">  
<title>canvas绘制图表</title>  
<style type="text/css">  
*{  
    margin:0;  
    padding:0;  
}  
body{  
    text-align:center;  
    background-color:black;  
}  
#c1{  
    background-color:white;  
}  
</style>  
<script type="text/javascript">  
function rnd(n,m){  
    return parseInt(Math.random()*(m-n)+n);  
}  
window.onload = function(){  
    var canvas = document.getElementById(‘c1‘);  
    var gd = canvas.getContext(‘2d‘); 

    var aData = http://www.mamicode.com/[100,200,300];  
    var space = 20;  
    var topSpace = 100;  

    var iMax=Math.max.apply(null,aData)  
    var w=40;  
    var lastR=0;    //前一个柱子的right  
    
    for(var i=0;i<3;i++){  
        //原点
        var l=lastR+space;  
        var t;

        //根据canvas 和 比例 来确定高, 而不是根据给出的高度    
        var h=(aData[i]/iMax)*(canvas.height-topSpace);  
         
         //原点
         t=canvas.height-h;  
        
        gd.fillStyle=‘rgb(‘+rnd(0, 256)+‘, ‘+rnd(0, 256)+‘, ‘+rnd(0, 256)+‘)‘;  
        
        gd.fillRect(l,t,w,h);  

        lastR=l+w;  
    }  
}  
</script>  
</head>  
<body>  
    <canvas width=‘500‘ height="500" id="c1"></canvas>  
</body>  
</html>  

 

canvas - 柱子效果