html5のキャンバスチャートにヒストグラムを実装する例
この記事では、キャンバス チャートを使用して HTML5 でヒストグラムを実装する例を主に紹介します。編集者がそれを参考として共有します。
数日前にチャートライブラリを使用しましたが、デフォルトでキャンバスを使用するチャートライブラリは、ビッグデータの処理に優れています。次に、canvas を使用してグラフ ライブラリを実装します。最初は簡単な棒グラフを実装しましょう。
効果は次のとおりです:
主な機能ポイントは次のとおりです:
テキストの描画
-
XY軸の描画。
データグループの描画 - アニメーションのデータ実装;
- マウスイベントの処理。
- 使い方
まずは、EChartsの使い方をいくつか参考にしながら、まずhtmlタグを渡してチャートを表示し、次にinitを呼び出して渡します。初期化中のデータ。
var con=document.getElementById('container'); var chart=new Bar(con); chart.init({ title:'全年降雨量柱状图', xAxis:{// x轴 data:['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'] }, yAxis:{//y轴 name:'水量', formatter:'{value} ml' }, series:[//分组数据 { 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] }, { name:'南部降水量', data:[12,10,17,25,27,39,50,38,100,30,56,90] }, { color:'hsla(270,80%,60%,1)', name:'北部降水量', data:[12,30,17,25,7,39,49,38,60,30,56,10] } ] });
class Chart{ constructor(container){ this.container=container; this.canvas=document.createElement('canvas'); this.ctx=this.canvas.getContext('2d'); this.W=1000*2; this.H=600*2; this.padding=120; this.paddingTop=50; this.title=''; this.legend=[]; this.series=[]; //通过缩小一倍,解决字体模糊问题 this.canvas.width=this.W; this.canvas.height=this.H; this.canvas.style.width = this.W/2 + 'px'; this.canvas.style.height = this.H/2 + 'px'; } }
class Bar extends Chart{ constructor(container){ super(container); this.xAxis={}; this.yAxis=[]; this.animateArr=[]; } init(opt){ Object.assign(this,opt); if(!this.container)return; this.container.style.position='relative'; this.tip=document.createElement('p'); this.tip.style.cssText='display: none; position: absolute; opacity: 0.5; background: #000; color: #fff; border-radius: 5px; padding: 5px; font-size: 8px; z-index: 99;'; this.container.appendChild(this.canvas); this.container.appendChild(this.tip); this.draw(); this.bindEvent(); } draw(){//绘制 } showInfo(){//显示信息 } animate(){//执行动画 } showData(){//显示数据 }
- measureText メソッドはテキストの描画に使用されます。テキストの幅を測定するために使用できるため、位置の競合を避けるために次の描画の位置を調整できます。
- 平行移動メソッドは描画コンテキスト (保存と復元の間) に配置でき、複雑な位置計算を回避できます。
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.textBaseLine='middle'; 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); ctx.restore(); } if(this.yAxis&&this.yAxis.name){ ctx.fillText(this.yAxis.name,padding,padding+paddingTop-30); } // x轴 ctx.save(); ctx.beginPath(); ctx.translate(padding,H-padding); ctx.moveTo(0,0); 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.stroke(); ctx.fillText(obj,x-xs/2,40); }); } ctx.restore(); // y轴 ctx.save(); ctx.beginPath(); ctx.strokeStyle='hsl(220,100%,50%)'; ctx.translate(padding,H-padding); ctx.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.fill(); 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; yl=info.num; ys=ydis/yl; //画Y轴刻度 ctx.save(); 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.stroke(); ctx.textAlign='right'; dim=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 に入れられます。ここでは、グループ化されたデータを展開し、前の 2 つのネストされた配列を 1 つのレイヤーに変換し、名前、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 }); }); index++; } this.animate(); }
アニメーションの実行
アニメーションの実行については何も言うことはなく、自己実行のクロージャ関数です。アニメーションの原理は、速度値 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++){ item=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); ctx.fillStyle=item.color; ctx.fillRect(that.padding+item.x,that.H-that.padding-item.y,item.w,item.y); ctx.restore(); isStop=false; } } if(isStop)return; requestAnimationFrame(run); }()) }
バインディングイベント
イベント 1: マウス移動時に、マウスの位置がグループ ラベルまたはデータ項目上にあるかどうかを確認し、true の場合は、パスを描画した後に isPointInPath(x,y) を呼び出します。 = 'ポインター'; データ項目の場合、列を再描画し、それを区別するために透明度を設定する必要があります。コンテンツも表示する必要があります。これは、親コンテナーに対して相対的に配置される p であり、初期化中にtip属性として設定されます。表示部分を showInfo メソッドにカプセル化します。
イベント 2: マウスダウンが発生すると、マウスがクリックしたグループ ラベルを決定し、対応するグループ データ シリーズに非表示属性を設定します。これが true の場合、項目が表示されないことを意味し、 draw メソッドを使用し、レンダリングと描画をオーバーライドし、アニメーションを実行します。bindEvent(){ 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(); 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]; 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; //选择数据项 for(var i=0,item,len=that.animateArr.length;i<len;i++){ item=that.animateArr[i]; ctx.save(); ctx.fillStyle=item.color; ctx.beginPath(); ctx.rect(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; ctx.fill(); canvas.style.cursor='pointer'; that.showInfo(pos,item); ctx.restore(); break; } canvas.style.cursor='default'; that.tip.style.display='none'; ctx.globalAlpha=1; ctx.fill(); 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 if(ctx.isPointInPath(pos.x*2,pos.y*2)){ that.series[i].hide=!that.series[i].hide; that.animateArr.length=0; that.draw(); break; } } },false); } //显示数据 showInfo(pos,obj){ var txt=this.yAxis.formatter?this.yAxis.formatter.replace('{value}',obj.num):obj.num; var 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 軸のサポートなど、さらに最適化する必要がある領域がまだ多くあります。 、コンテンツ効果の表示、ポリライン機能などもサポートしています。
関連する推奨事項: カラー ブロックを動的に表示するレポート効果を実現するHTML (サンプル コード)
ヒストグラム (棒グラフ) 効果を生成する HTML5 サンプル コード
以上がhtml5のキャンバスチャートにヒストグラムを実装する例の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











H5は、セマンティック要素とARIA属性を介して、WebページのアクセシビリティとSEO効果を改善します。 1.使用などを使用して、コンテンツ構造を整理し、SEOを改善します。 2。ARIA-LabelなどのARIA属性はアクセシビリティを強化し、支援技術ユーザーはWebページをスムーズに使用できます。

H5ReferStoHtml5、apivotaltechnologyinwebdevelopment.1)html5introduceSnewelementsandapisforrich、dynamicwebapplications.2)Itupp ortsmultimediawithoutplugins、endancingurexperiencecrossdevices.3)semanticelementsimprovecontentstructurendseo.4)H5'srespo

H5コードのベストプラクティスには以下が含まれます。1。正しいDoctype宣言と文字エンコーディングを使用します。 2。セマンティックタグを使用します。 3。HTTPリクエストを削減します。 4.非同期負荷を使用します。 5。画像を最適化します。これらのプラクティスは、Webページの効率、保守性、ユーザーエクスペリエンスを向上させることができます。

Web標準とテクノロジーは、これまでにHTML4、CSS2、および単純なJavaScriptから進化し、重要な開発を受けてきました。 1)HTML5は、CanvasやWebstorageなどのAPIを導入し、Webアプリケーションの複雑さと互換性を高めます。 2)CSS3はアニメーション関数とトランジション関数を追加して、ページをより効果的にします。 3)JavaScriptは、矢印関数やクラスなど、node.jsおよびES6の最新の構文を通じて開発効率とコードの読みやすさを向上させます。これらの変更により、パフォーマンスの最適化とWebアプリケーションのベストプラクティスの開発が促進されました。

H5開発で習得する必要があるツールとフレームワークには、Vue.JS、React、Webpackが含まれます。 1.Vue.jsは、ユーザーインターフェイスの構築に適しており、コンポーネント開発をサポートします。 2.複雑なアプリケーションに適した仮想DOMを介したページレンダリングを最適化します。 3.Webpackは、モジュールのパッケージングに使用され、リソースの読み込みを最適化します。

H5はHTML5の略語だけでなく、より広い最新のWeb開発テクノロジーエコシステムを表しています。1。H5にはHTML5、CSS3、JavaScript、および関連するAPIおよびテクノロジーが含まれます。 2.より豊かでインタラクティブでスムーズなユーザーエクスペリエンスを提供し、複数のデバイスでシームレスに実行できます。 3. H5テクノロジースタックを使用して、レスポンシブWebページと複雑なインタラクティブ機能を作成できます。

H5とHTML5は、同じこと、つまりHTML5を参照します。 HTML5はHTMLの5番目のバージョンであり、セマンティックタグ、マルチメディアサポート、キャンバスとグラフィックス、オフラインストレージ、ローカルストレージなどの新しい機能をもたらし、Webページの表現力と互換性を向上させます。

html5hassificlytransformdedwebdeveverment byintroducingsingingelements、endincemultimediasupport、およびrequrovingperformance.1)itmadewebsitesmoreaccessibleandseo-frendlywithsemantelementslike、and.2)
