canvas自定義資料圓環
阿新 • • 發佈:2020-09-21
原文: 本人掘金文章
關注公眾號: 微信搜尋 web全棧進階
; 收貨更多的乾貨
我工作中常用視覺化外掛: 百度的echarts、mapv
;阿里的antv
系列;以及three.js
;
當外掛有時滿足不了我們相對應的需求(資料圓環)、UI又要求必須這樣時, 這時就要考慮自定義了;
一、效果圖
二、HTML
<canvas id="canvas" width="250" height="170"></canvas>
三、JS
let canvas = document.getElementById('canvas'); let ctx = canvas.getContext('2d'); // 填充畫布 ctx.fillStyle= 'transparent'; ctx.fillRect(0,0, 150, 150); ctx.beginPath(); // 初始化畫布起點 ctx.translate(250/2, 170/2); // 起點 ctx.moveTo(0,0); // 畫大圓 ctx.arc(0,0, 60,0,Math.PI*2,false); ctx.closePath(); ctx.fillStyle='transparent'; ctx.fill(); // 動態環比 let arr = ['0.85', '0.15'] let beginDeg = Math.PI * 1.5 let endDeg = Math.PI * 1.5 arr.forEach((t, index) => { endDeg = beginDeg + (2 * Math.PI * t); ctx.beginPath(); ctx.moveTo(0, 0); ctx.arc(0, 0, 60, beginDeg, endDeg, false); if (index < 1) beginDeg = endDeg ctx.closePath(); ctx.fillStyle = index === 0 ? '#f00' : '#ff0'; ctx.fill(); // 使某部分圓環變小,且在最外邊; 效果圖黃色部分 if (index === 1) { ctx.beginPath(); ctx.moveTo(0,0); ctx.arc(0,0,56,beginDeg, endDeg,false); ctx.closePath(); ctx.fillStyle= '#000'; ctx.fill(); } }) //變成圈圖,中間加點東西 ctx.beginPath(); ctx.arc(0, 0, 50, 0,Math.PI * 2, true); ctx.closePath(); ctx.fillStyle = "#000"; ctx.fill(); //繪製文字 ctx.moveTo(0,0);//移動筆觸到原點 ctx.fillStyle = 'white';//文字顏色 ctx.font="20px normal "; ctx.textAlign="center";//相對原點水平居中 ctx.textBaseline="middle";//相對原點垂直居中 ctx.fillText("88.8%",0,-8); ctx.moveTo(0,0);//移動筆觸到原點 ctx.fillStyle = 'white';//文字顏色 ctx.font='15px normal ';//文字 ctx.textAlign="center";//相對原點水平居中 ctx.textBaseline="middle";//相對原點垂直居中 ctx.fillText('離線率',0,15);//開始寫字
四、結語
有段時間沒有使用canvas了,實現這個圓環也是比較粗糙;有的業務邏輯的繪製去掉了,沒上傳。