`
niyigeren
  • 浏览: 3705 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

html5,css,canvas

阅读更多
目的实现:在使用Canvas画板,画饼图之后,在饼图上显示字体,及一些其他信息;
状态:完成;
参考资料:
   html5 w3网站的
   http://www.w3school.com.cn/tags/canvas_arc.asp;
   安卓实现资料
   http://www.kaifazhe.com/mobile/397332.html
  
现在细谈代码:
   画图饼代码和扇形:
   <script type="text/javascript">
//获取Canvas对象(画布)
var canvas = document.getElementById("myCanvas");
//简单地检测当前浏览器是否支持Canvas对象,以免在一些不支持html5的浏览器中提示语法错误
if(canvas.getContext){ 
    //获取对应的CanvasRenderingContext2D对象(画笔)
    var ctx = canvas.getContext("2d");
  
    ctx.beginPath();
    ctx.arc(width/2,height/2,scaleAnimation *     pieRadius,cumulativeAngle,cumulativeAngle + segmentAngle,false);
ctx.lineTo(width/2,height/2);
ctx.closePath();
ctx.fillStyle = data[i].color;
ctx.fill();
    }
  
</script>
  填充文字代码:
  var addvalue=0;
for(var i=0; i<data.length; i++){
ctx.font='20px 微软雅黑';
    ctx.strokeStyle='#000000';
    CalcArcEndPointXY(width/2,height/2,pieRadius/2,addvalue+360*(data[i].value/segmentTotal)/2);
    ctx. strokeText(data[i].name+":"+data[i].value/segmentTotal*100.00+"%",posX,posY);
                    addvalue+=360*(data[i].value/segmentTotal);

}

  附加一个算位置的函数,这个是必须的
  //求扇形的中心坐标
        function CalcArcEndPointXY(cirX, cirY, radius, cirAngle){
   //将角度转换为弧度
var arcAngle =  (cirAngle*Math.PI/ 180.0);
if (cirAngle < 90)
{
    //alert(cirX+Math.cos(arcAngle)*radius);
posX= cirX + Math.cos(arcAngle)*radius;
                posY= cirY +(Math.sin(arcAngle)) * radius;
}
else if (cirAngle == 90)
{
posX = cirX;
posY = cirY + radius;
}
else if (cirAngle > 90 && cirAngle < 180)
{
arcAngle =  (Math.PI * (180 - cirAngle) / 180.0);
posX = cirX - (Math.cos(arcAngle)) * radius;
posY = cirY +(Math.sin(arcAngle)) * radius;
}
else if (cirAngle == 180)
{
posX = cirX - radius;
posY = cirY;
}
else if (cirAngle > 180 && cirAngle < 270)
{
arcAngle = (Math.PI * (cirAngle - 180) / 180.0);
posX = cirX -(Math.cos(arcAngle)) * radius;
posY = cirY -(Math.sin(arcAngle)) * radius;
}
else if (cirAngle == 270)
{
posX = cirX;
posY = cirY - radius;
}
else
{
arcAngle =  (Math.PI * (360 - cirAngle) / 180.0);
posX = cirX + (Math.cos(arcAngle)) * radius;
posY = cirY - (Math.sin(arcAngle)) * radius;
}
}
上面几个单独使用的话,都很简单,麻烦的是,一起使用定位的时候,请注意选好画图的起始位置,这是重点,否则字体的位置定位不准确。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics