繪製canvas圓形統計圖插件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>插件繪製圓形統計圖插件效果</title>
<style>
*{padding:0px; margin:0px;}
</style>
</head>
<body>
<canvas  id="canvas" width="110" height="110"></canvas>
<script type="text/javascript">
window.onload = function(){ 
function drawCircle(_options){
    var options = _options || {};    //獲取或定義options對象;
    options.angle = options.angle || 1;
    options.color = options.color || '#fff';
    options.lineWidth = options.lineWidth || 10;
    options.lineCap = options.lineCap || 'square'; //結束帽ctx.lineCap="round"; 這種表示圓形的結束帽

    var oBoxOne = document.getElementById(options.id);
    var sCenter = oBoxOne.width / 2;
    var ctx = oBoxOne.getContext('2d');
    var nBegin = Math.PI / 2;
    var nEnd = Math.PI * 2;
    var grd = ctx.createLinearGradient(0, 0, oBoxOne.width, 0);
    grd.addColorStop(0, 'red');
    grd.addColorStop(0.5, 'yellow');
    grd.addColorStop(1, 'green');

    ctx.textAlign = 'center';
    ctx.font = 'normal normal bold 20px Arial';
    ctx.fillStyle = options.color == 'grd' ? grd : options.color;
    ctx.fillText((options.angle * 100) + '%', sCenter, sCenter);
    /*ctx.strokeStyle = grd;
    ctx.strokeText((options.angle * 100) + '%', sCenter, sCenter);*/
    ctx.lineCap = options.lineCap;
    ctx.strokeStyle = options.color == 'grd' ? grd : options.color;
    ctx.lineWidth = options.lineWidth;

    ctx.beginPath();
    ctx.strokeStyle = '#D8D8D8';
    ctx.arc(sCenter, sCenter, (sCenter - options.lineWidth), -nBegin, nEnd, false);
    ctx.stroke();
   //getImageData() 複製畫布上指定矩形的像素數據,然後通過 putImageData() 將圖像數據放回畫布:
    var imd = ctx.getImageData(0, 0, 240, 240);
    function draw(current) {
        ctx.putImageData(imd, 0, 0);
        ctx.beginPath();
        ctx.strokeStyle = options.color == 'grd' ? grd : options.color;
        ctx.arc(sCenter, sCenter, (sCenter - options.lineWidth), -nBegin, (nEnd * current) - nBegin, false);
        ctx.stroke();
    }

    var t = 0;
    var timer = null;
    function loadCanvas(angle) {
        timer = setInterval(function(){
            if (t > angle) {
                draw(options.angle);
                clearInterval(timer);
            }else{
                draw(t);
                t += 0.02;
            }
        }, 20);
    }
    loadCanvas(options.angle);
    timer = null;

}

drawCircle({
    id: 'canvas',
    color: '#00BCD4',
    angle: 0.95,
    lineWidth: 5
});



}
</script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章