html5+canvas에서 원형 차트를 동적으로 구현하는 단계에 대한 자세한 설명

php中世界最好的语言
풀어 주다: 2018-05-07 17:45:39
원래의
3668명이 탐색했습니다.

이번에는 html5+canvas를 사용하여 원형 차트를 동적으로 구현하는 단계에 대해 자세히 설명하겠습니다. html5+canvas를 사용하여 원형 차트를 동적으로 구현하는 경우 주의 사항은 무엇입니까? 바라보다.

먼저 렌더링을 살펴보겠습니다

jquery와 같은 타사 라이브러리를 참조하지 않고 dom 연산 및 캔버스 기능을 사용하여 작성되었습니다.

캔버스에 그린 원은 일반적으로 속이 빈 원과 속이 빈 원으로 구분됩니다.

수요 분석을 바탕으로 우리는 원이 견고한 원이라는 것을 알고 있습니다.

1. 먼저 캔버스를 사용하여 단단한 원을 그립니다

//伪代码
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(圆心x轴坐标,圆心y轴坐标,半径,开始角,结束角);
ctx.fillStyle = 'green';
ctx.closePath();
ctx.fill();
로그인 후 복사

2. 다양한 색상에 따라 원형 차트를 그립니다.

//伪代码
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(圆心x轴坐标,圆心y轴坐标,半径,绿色开始角,绿色结束角);
ctx.fillStyle = 'green';
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.arc(圆心x轴坐标,圆心y轴坐标,半径,红色开始角,红色结束角);
ctx.fillStyle = 'red';
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.arc(圆心x轴坐标,圆心y轴坐标,半径,黄色开始角,黄色结束角);
ctx.fillStyle = 'yellow';
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.arc(圆心x轴坐标,圆心y轴坐标,半径,紫色开始角,紫色结束角);
ctx.fillStyle = 'purple';
ctx.closePath();
ctx.fill();
로그인 후 복사

3. 동적으로 원형 차트를 그립니다.

일반적으로 권장되는 세 가지 방법이 있습니다. 인터넷상의 원: requestAnimationFrame, setInterval(타이밍) 및 동적 각도 계산.

여기에서는 첫 번째 requestAnimationFrame 메서드를 사용합니다.

작성 과정에서 문제를 발견했습니다. 즉, 원을 동적으로 그릴 때 원의 중심 좌표를 기준으로 그려지지 않습니다. 이 문제를 해결하려면 원을 그릴 때마다 캔버스 브러시의 좌표를 원래 원 중심의 좌표로 다시 정의해야 합니다.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <style>
        #graph {
/*            border: 1px solid black;
            height: 100%;
            width: 100%;
            box-sizing: border-box;*/
        }
    </style>
</head>
<body>
<p id="circle" style="width: 500px;float: left;"></p>
</body>
</html>
<script type="text/javascript">
(function(window,undefined){
    var data = [
        {"product":"产品1","sales":[192.44 ,210.54 ,220.84 ,230.11 ,220.85 ,210.59 ,205.49 ,200.55 ,195.71 ,187.46 ,180.66 ,170.90]},
        {"product":"产品2","sales":[122.41 ,133.16 ,145.65 ,158.00 ,164.84 ,178.62 ,185.70 ,190.13 ,195.53 ,198.88 ,204.32 ,210.91]},
        {"product":"产品3","sales":[170.30 ,175.00 ,170.79 ,165.10 ,165.62 ,160.92 ,155.92 ,145.77 ,145.17 ,140.27 ,135.99 ,130.33]},
        {"product":"产品4","sales":[165.64 ,170.15 ,175.10 ,185.32 ,190.90 ,190.01 ,187.05 ,183.74 ,177.24 ,181.90 ,179.54 ,175.98]}
    ]
        
    var dom_circle = document.getElementById('circle');
    if(dom_circle != undefined && dom_circle != null)
    {
        var canvas = document.createElement("canvas");
        dom_circle.appendChild(canvas);
        var ctx = canvas.getContext('2d');
        var defaultStyle = function(Dom,canvas){
            if(Dom.clientWidth <= 300)
            {
                canvas.width = 300;
                Dom.style.overflowX = "auto";
            }
            else{
                canvas.width = Dom.clientWidth;
            }
            if(Dom.clientHeight <= 300)
            {
                canvas.height = 300;
                Dom.style.overflowY = "auto";
            }
            else
            {
                canvas.height = Dom.clientHeight;
            }
            //坐标轴区域
            //注意,实际画折线图区域还要比这个略小一点
            return {
                p1:&#39;green&#39;,
                p2:&#39;red&#39;,
                p3:&#39;yellow&#39;,
                p4:&#39;purple&#39;,
                x: 0 ,    //坐标轴在canvas上的left坐标
                y: 0 ,    //坐标轴在canvas上的top坐标
                maxX: canvas.width ,   //坐标轴在canvas上的right坐标
                maxY: canvas.height ,   //坐标轴在canvas上的bottom坐标
                r:(canvas.width)/2,  //起点
                ry:(canvas.height)/2,  //起点
                cr: (canvas.width)/4, //半径
                startAngle:-(1/2*Math.PI),               //开始角度
                endAngle:(-(1/2*Math.PI)+2*Math.PI),     //结束角度
                xAngle:1*(Math.PI/180)                   //偏移量
            };
        }
        //画圆
        var tmpAngle = -(1/2*Math.PI);
        var ds = null;
        var sum = data[0][&#39;sales&#39;][0]+data[0][&#39;sales&#39;][1]+data[0][&#39;sales&#39;][2]+data[0][&#39;sales&#39;][3]
        var percent1 = data[0][&#39;sales&#39;][0]/sum * Math.PI * 2 ;
        var percent2 = data[0][&#39;sales&#39;][1]/sum * Math.PI * 2 + percent1;
        var percent3 = data[0][&#39;sales&#39;][2]/sum * Math.PI * 2 + percent2;
        var percent4 = data[0][&#39;sales&#39;][3]/sum * Math.PI * 2 + percent3;
        console.log(percent1);
        console.log(percent2);
        console.log(percent3);
        console.log(percent4);
        var tmpSum = 0;
        var drawCircle = function(){
            
            
            if(tmpAngle >= ds.endAngle)
            {
                return false;
            }
            else if(tmpAngle+ ds.xAngle > ds.endAngle)
            {
                tmpAngle = ds.endAngle;
            }
            else{
                tmpAngle += ds.xAngle;
                tmpSum += ds.xAngle
            }
            // console.log(ds.startAngle+'***'+tmpAngle);
            // console.log(tmpSum);
            // ctx.clearRect(ds.x,ds.y,canvas.width,canvas.height);
            
            if(tmpSum > percent1 && tmpSum <percent2)
            {
                ctx.beginPath();
                ctx.moveTo(ds.r,ds.ry);
                ctx.arc(ds.r,ds.ry,ds.cr,ds.startAngle+percent1,tmpAngle);
            
                ctx.fillStyle = ds.p2;
            }
            else if(tmpSum > percent2 && tmpSum <percent3)
            {
                ctx.beginPath();
                ctx.moveTo(ds.r,ds.ry);
                ctx.arc(ds.r,ds.ry,ds.cr,ds.startAngle+percent2,tmpAngle);
                ctx.fillStyle = ds.p3;
            }
            else if(tmpSum > percent3 )
            {
                ctx.beginPath();
                ctx.moveTo(ds.r,ds.ry);
                ctx.arc(ds.r,ds.ry,ds.cr,ds.startAngle+percent3,tmpAngle);
                ctx.fillStyle = ds.p4;
            }
            else{
                ctx.beginPath();
                ctx.moveTo(ds.r,ds.ry);
                ctx.arc(ds.r,ds.ry,ds.cr,ds.startAngle,tmpAngle);
                ctx.fillStyle = ds.p1;
            }
            ctx.closePath();
            ctx.fill();
            requestAnimationFrame(drawCircle);
        }
        this.toDraw = function(){
            ds= defaultStyle(dom_circle,canvas);
            // console.log(tmpAngle);
            // console.log(ds.xAngle)
            ctx.clearRect(ds.x,ds.y,canvas.width,canvas.height);
            drawCircle();
        }
        this.toDraw();
        var self = this;
        window.onresize = function(){
            self.toDraw()
        }
    }
})(window);    
</script>
로그인 후 복사

이 기사의 사례를 읽으신 후 방법을 마스터하셨다고 생각합니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사를 주목하세요!

추천 도서:

H5+WebWorkers 멀티스레드 개발 및 사용법 상세 설명

H5 오프라인 애플리케이션 및 클라이언트 스토리지 사용법 상세 설명

위 내용은 html5+canvas에서 원형 차트를 동적으로 구현하는 단계에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!