며칠 전에 차트 라이브러리를 사용했는데 그중 Baidu의 ECharts가 가장 좋은 것 같습니다. 기본적으로 캔버스를 사용합니다. 빅 데이터 처리에는 캔버스 차트가 더 좋습니다. 그런 다음 캔버스를 사용하여 차트 라이브러리를 구현하겠습니다. 먼저 간단한 막대 차트를 구현해 보겠습니다.
효과는 다음과 같습니다. 주요 기능 포인트는 다음과 같습니다:먼저 사용 방법을 살펴보겠습니다. 몇 가지 ECharts 사용 방법을 참조합니다. 먼저 html 태그를 전달하여 차트를 표시한 다음 init를 호출하고 초기화 중에 데이터를 전달합니다.
var con=document.getElementById('container'); varchart=new Bar(con);chart.init({ title:'연중 강우량 히스토그램', xAxis:{// x축 데이터: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'] }, yAxis:{//y축 이름:'물량', 포맷터:'{value} ml' }, 계열:[//그룹 데이터{ name:'동쪽 강수량', data:[62,20,17,45,100,56,19,38,50,120,56,130] }, { name:'서쪽 강수량', data:[52,10,17 ,25 ,60,39,19,48,70,30,56,8] }, { 이름:'남부강수량', data:[12,10,17,25,27,39,50,38,100,30,56,90] }, { color:'hsla(270,80%,60%,1)', name:'북부 강수량 수량', 데이터:[12,30,17,25,7,39,49,38,60,30,56,10] } ] });
차트 베이스 클래스에 대해서는 나중에 파이차트, 라인차트도 작성할 예정이므로 공통되는 부분을 추출해보겠습니다. canvas.style.width와 canvas.width는 서로 다릅니다. 전자는 그래픽을 늘리는 반면, 후자는 우리가 일반적으로 사용하는 것이며 그래픽을 늘리지 않습니다. 여기서 먼저 확장하고 축소한 후 작성하는 목적은 캔버스에 텍스트를 그릴 때 흐려지는 문제를 해결하기 위한 것입니다.
class Chart{ constructor(container){ this.container=container; this.canvas=document.createElement('canvas'); this.ctx=this.canvas.getContext('2d'); this.H=600*2; this.paddingTop=50; this.legend=[]; this.series=[]; //크기를 두 배로 늘려 글꼴 흐림 문제를 해결합니다. this.canvas.height=this.H; 2 + 'px'; this.canvas.style.height = this.H/2 + 'px' } }
히스토그램을 초기화하려면 es6에서 Object.sign(this,opt)을 호출하세요. 이는 현재 인스턴스에 속성을 복사하는 JQ의 확장 메서드와 동일합니다. 동시에 html 태그인 팁 속성도 생성되며 나중에 데이터 정보를 표시하는 데 사용됩니다. 그런 다음 그래픽을 그리고 마우스 이벤트를 바인딩합니다.
클래스 Bar 확장 차트{ constructor(container){ super(container); this.xAxis=[] this.animateArr=[] } init(this,opt) ; if(!this.container)return; this.container.style.position='relative'; this.tip=document.createElement('div'); this.tip.style.cssText='display: 없음; 불투명도: 0.5; 색상: #fff; 글꼴 크기: 8px; : 99;'; this.container.appendChild(this.canvas); this.draw(); this.bindEvent(); } draw(){//드로잉} showInfo(){//정보 표시} animate(){//애니메이션 수행} showData(){//데이터 표시}
XY축 그리기
먼저 제목을 그린 다음 XY축을 그리고 복잡한 계산이 포함된 그룹화된 데이터 시리즈를 순회한 다음 XY축의 스케일을 그리고 그룹 레이블을 그리고 마지막으로 데이터를 그립니다. 데이터 항목 계열은 X축의 xAxis.data에 1:1로 대응되는 그룹화된 데이터이다. 각 항목은 사용자 정의된 이름과 색상을 가질 수 있습니다. 지정하지 않으면 이름이 nunamed에 부여되고 색상이 자동으로 생성됩니다. 범례 속성은 태그 목록 정보를 기록하는 데에도 사용됩니다. 이는 후속 마우스 클릭에서 클릭이 올바른지 확인하는 데 유용하기 때문입니다.
캔버스의 주요 지식 포인트:
draw(){ var that=this, ctx=this.ctx, canvas=this.canvas, W=this.W, H=this.H, padding=this.padding, paddingTop=this.paddingTop, xl=0,xs=0,xdis=W-padding*2,//x축 단위 수, 각 단위 길이, x축 전체 길이 yl=0,ys=0,ydis=H-padding* 2-paddingTop; //y축 단위의 개수, 각 단위의 길이, y축의 전체 길이 ctx.fillStyle='hsla(0,0%,20%,1)'; ctx.StrokeStyle='hsla(0,0%,10%,1)'; ctx.lineWidth=1;ctx.textAlign='center'; ctx.font='24px arial'; ctx.clearRect(0,0,W,H); if(this.title){ ctx.save(); ctx.textAlign='left'; ctx.font='bold 40px arial'; ctx.fillText(this.title,padding-50,70) } if(this.yAxis&&this.yAxis.name) { ctx.fillText(this.yAxis.name,padding,padding+paddingTop-30) } // x축 ctx.save(); ctx.translate(padding,H-padding) ctx.lineTo(W-2*padding,0); ctx .Stroke(); // x축 스케일 if(this.xAxis&&(xl=this.xAxis.data.length)){ xs=(W-2*padding)/xl; this.xAxis.data.forEach((obj,i)=>{ var x=xs*(i+1); ctx.moveTo(x,0); ctx. lineTo(x,10); ctx.fillText(obj,x-xs/2,40) }) ctx.restore(); // y축 ctx.save(); ctx.StrokeStyle='hsl(220,100%,50%)'; . moveTo(0,0); ctx.lineTo(0,2*padding+paddingTop-H); ctx.Stroke(); ctx.restore(); if(this.series.length){ var curr,txt,dim,info,item,tw=0; for(var i=0;i<this.series.length) ;i++){ item=this.series[i]; if(!item.data||!item.data.length){ this.series.splice(i--,1);continue; 색상 없이 항목 할당 if(!item.color){ var hsl=i%2?180+20*i/2:20*(i-1); item.color='hsla('+hsl+',70% , 60%,1)'; } item.name=item.name||'unnamed'; // 그룹화 라벨 그리기 ctx.save(); ctx.translate(padding+W/4,paddingTop+40); that.legend.push({ hide:item.hide||false, name:item.name, color:item.color, x:padding+that.W /4+i*90+tw, y:paddingTop+40, w:60, h:30, r:5 }) ctx.textAlign='left'; ctx.fillStyle=item.color; ctx.StrokeStyle=item.color; roundRect(ctx,i*90+tw,0,60,30,5); ctx.globalAlpha=item.hide?0.3:1; ();ctx.fillText(item.name,i*90+tw+70,26); tw+=ctx.measureText(item.name).width;//문자 길이 계산 ctx.restore(); if(item.hide)continue; //Y축 스케일로 데이터 계산 if(!info){ info=calculateY( item.data.slice(0,xl)); } curr=calculateY(item.data.slice(0,xl)); if(curr.max>info.max) info=curr; } } if(!info) return; ys=ydis/yl; //Y축 스케일 그리기 ctx.fillStyle='hsl(200,100%,60%) ) '; ctx.translate(padding,H-padding); for(var i=0;i<=yl;i++){ ctx.beginPath(); ctx.StrokeStyle='hsl(220,100%,50%)'; ctx.moveTo(-10,-Math.floor(ys*i)) ctx.lineTo(0,-Math.floor(ys*i)); ctx.Stroke(); ctx.beginPath(); ctx.StrokeStyle='hsla(0,0%,80%,1)'; ctx.moveTo(0,-Math.floor(ys*i)); ctx.lineTo(xdis,-Math.floor(ys*i)) ctx.textAlign='right'; Math.min(Math.floor(info.step*i),info.max); txt=this.yAxis.formatter?this.yAxis.formatter.replace('{value}',dim):dim.ctx.fillText(txt,-20,-ys*i+10) } ctx.restore() ; //데이터 그리기 this.showData(xl,xs,info.max) }}플롯 데이터
데이터 항목은 마우스가 그 위로 슬라이드할 때 이후에 애니메이션을 적용하고 표시해야 하므로 애니메이션 대기열 animateArr에 배치됩니다. 여기서는 그룹화된 데이터를 확장하고 이전 두 개의 중첩 배열을 하나의 레이어로 변환하고 이름, x 좌표, y 좌표, 너비, 속도 및 색상과 같은 각 데이터 항목의 속성을 계산해야 합니다. 데이터가 정리된 후 애니메이션이 실행됩니다.
showData(xl,xs,max){ //데이터 그리기 var that=this, ctx=this.ctx, ydis=this.H-this.padding*2-this.paddingTop, sl=this.series.filter(s= >!s.hide).length, sp=Math.max(Math.pow(10-sl,2)/3-4,5), w=(xs-sp*(sl+1))/sl, h,x,index=0; that.animateArr.length=0; // 데이터 항목을 확장하고 애니메이션 대기열을 채웁니다. for(var i=0 ,item ,len=this.series.length;i<len;i++){ item=this.series[i]; if(item.hide)continue; item.data.slice(0,xl).forEach((d,j)=>{ h=d/max*ydis; x=xs*j+w*index+sp*(index+1); that.animateArr .push({ index:i, name:item.name, num:d, x:Math.round(x), y:1, w:Math.round(w), h:Math.floor(h+ 2) , vy:Math.max(300,Math.floor(h*2))/100, color:item.color }) });애니메이션 실행
애니메이션 실행에 관해 특별히 언급할 내용은 없으며 단지 자체 실행 폐쇄 기능일 뿐입니다. 애니메이션의 원리는 속도 값 vy를 y축에 순차적으로 누적하는 것입니다. 하지만 대기열이 애니메이션 실행을 마치면 중지해야 하므로 대기열 실행이 완료될 때마다 판단되는 isStop 플래그가 있다는 점을 기억하세요.
animate(){ var that=this, ctx=this.ctx, isStop=true; (function run(){ isStop=true; for(var i=0,item;i<that.animateArr.length;i++){ 항목 =that.animateArr[i]; if(item.y-item.h>=0.1){ item.y=item.h } else { item.y+=item.vy; } if(item.y<item.h){ ctx.save(); // ctx.translate(that.padding+item.x,that.H-that.padding); .fillRect(that.padding+item.x,that.H-that.padding-item.y,item.w,item.y) ctx.restore(); isStop=false } } if(isStop)returnAnimationFrame(run) }())}바인딩 이벤트
이벤트 1: 마우스 이동 시 마우스 위치가 그룹 라벨에 있는지, 아니면 데이터 항목에 있는지 확인하고, true인 경우 isPointInPath(x,y)를 호출합니다. 데이터 항목, 열을 다시 그려야 하고 투명도를 설정하고 구별해야 합니다. 콘텐츠도 표시되어야 합니다. 여기에는 초기화 중에 팁 속성이 설정되어 있는 상위 컨테이너 컨테이너를 기준으로 한 div가 있습니다. 표시 부분을 showInfo 메소드로 캡슐화합니다.
이벤트 2: mousedown이 발생하면 마우스가 어떤 그룹 라벨을 클릭하는지 확인하고, 해당 그룹 데이터 계열에 hide 속성을 설정한 후 true이면 해당 항목이 표시되지 않는다는 의미이며, draw 메소드를 호출합니다. , 렌더링 및 그리기를 재정의하고 애니메이션을 수행합니다.
binEvent(){ var that=this, canvas=this.canvas, ctx=this.ctx; this.canvas.addEventListener('mousemove',function(e){ var isLegend=false; // pos=WindowToCanvas(canvas,e .clientX,e.clientY); var box=canvas.getBoundingClientRect(); x:e.clientX-box.left, y:e.clientY-box.top }; // 그룹화 라벨 for(var i=0,item,len=that.legend.length;i<len;i++){ item =that.legend[i]; ctx.save(); roundRect(ctx,item.x,item.y,item.w,item.h,item.r); 두 배이므로 좌표는 *2입니다. if(ctx.isPointInPath(pos.x*2,pos.y*2)){ canvas.style.cursor='pointer'; ctx.restore(); isLegend=true ; break; } canvas.style.cursor='default'; ctx.restore(); } if(isLegend) return; i=0,item,len=that.animateArr.length;i<len;i++){ item=that.animateArr[i] ctx.fillStyle=item.color(); ctx.direct(that.padding+item.x,that.H-that.padding-item.h,item.w,item.h); if(ctx.isPointInPath(pos.x*2,pos.y*2)){ //그래픽을 지우고 투명도 0.5로 다시 그립니다. ctx.clearRect(that.padding+item.x,that.H-that .padding-item.h,item.w,item.h); ctx.globalAlpha=0.5; canvas.style.cursor='포인터'; that.showInfo(pos,item); break; } canvas.style.cursor='none'; ctx.globalAlpha=1; ); ctx.restore(); } },false); this.canvas.addEventListener('mousedown',function(e){ e.preventDefault(); var box=canvas.getBoundingClientRect(); var pos = { x:e.clientX-box.left, y:e.clientY-box.top } for(var i=0,item,len =that.legend.length;i<len;i++){ item=that.legend[i]; roundRect(ctx,item.x,item.y,item.w,item.h,item.r); // 2배이므로 좌표는 *2입니다. if(ctx.isPointInPath(pos.x*2, pos) .y*2)){ that.series[i].hide=!that.series[i].hide; that.animateArr.length=0; that.draw() } },false); } //데이터 표시 showInfo(pos,obj){ var txt=this.yAxis.formatter?this.yAxis.formatter.replace('{value}',obj.num):obj.num; box=this.canvas.getBoundingClientRect(); var con=this.container.getBoundingClientRect(); this.tip.innerHTML = '<p>'+obj.name+':'+txt+'</p>'; this.tip.style.left=(pos.x+(box.left-con.left)+10 )+'px'; this.tip.style.top=(pos.y+(box.top-con.top)+10)+'px'; this.tip.style.display='block' }요약
여기서 완성된 것은 기본적인 효과일 뿐입니다. 사실 반응형 지원, 모바일 지원, 애니메이션 효과, 다Y축 지원, 디스플레이 콘텐츠 효과, 폴리라인 기능 지원 등 더 최적화해야 할 영역이 많습니다. .
위 내용은 이 기사의 전체 내용입니다. 모든 분들의 학습에 도움이 되기를 바랍니다. 또한 모든 분들이 VeVb Wulin Network를 지지해 주시길 바랍니다.