css
*{ margin: 0; padding: 0; margin-top: 10vh; } body{ text-align: center; } canvas{ margin: 0 auto; border: 1px solid #CCCCCC; }
js
<script type="text/javascript"> window.addEventListener(‘load‘,function(){ var canvas = document.createElement(‘canvas‘) document.body.appendChild(canvas) canvas.id = ‘myCanvas‘ canvas.width = 400; canvas.height= 400; var myCanvas = document.getElementById(‘myCanvas‘) //检测浏览器是否支持canvas属性 if(!myCanvas||!myCanvas.getContext){ return } var ctx = myCanvas.getContext(‘2d‘) drawScreen() function drawScreen(){ var deg = Math.PI/180 var obj = { x:200, y:200, r:80, sDeg:[30,111,190,233,280,345], eDeg:[111,190,233,280,345,30], style:[‘#f00‘,‘#0f0‘,‘#00f‘,‘#789‘,‘#abcdef‘] } for (var i = 0; i < obj.sDeg.length; i++) { drawPie(ctx,obj.x, obj.y, obj.r, obj.sDeg[i] * deg, obj.eDeg[i] * deg); ctx.fill(); ctx.fillStyle = obj.style[i]; } } function drawPie(ctx,x,y,r,sDeg,eDeg){ //保存初始状态 ctx.save() //位移到目标点 ctx.translate(x,y) ctx.beginPath() //画出圆弧 ctx.arc(0,0,r,sDeg,eDeg) //再次保存以备旋转 ctx.save() //旋转至起始角度 ctx.rotate(eDeg) //移动到终点,连接终点与圆心 ctx.moveTo(r,0) ctx.lineTo(0,0) //还原 ctx.restore() //旋转至起点位置 ctx.rotate(sDeg) //从圆心连接到起点位置 ctx.lineTo(r,0) ctx.closePath() //还原到最初的状态 ctx.restore() } },false) </script>
时间: 2024-11-10 14:04:07