本文介绍了六边形战斗力属性图绘制,涉及知识点canvas
由于正多边形是十分规则的,所以感觉很轻易就可以用h5 canvas来实现,首先在里画一个canvas,id="polygon"。
<canvas id ="polygon"><canvas>
等待页面加载完毕后开始绘制。函数polygon传入几个参数:canvas对象,多边形边数,颜色渐变层数,各项能力值(数组),各项能力的名称(数组),调用polygon就能绘制出想要的能力属性图啦。
(function(){
varhex=document.getElementById("polygon");
varability_value=[];
varability_name=[];
//设置能力值
ability_value[0]=0.8;
ability_value[1]=0.5;
ability_value[2]=0.7;
ability_value[3]=0.6;
ability_value[4]=0.5;
ability_value[5]=0.7;
//设置能力属性名
ability_name[0]="物理";
ability_name[1]="魔法";
ability_name[2]="韧性";
ability_name[3]="敏捷";
ability_name[4]="防御";
ability_name[5]="智力";
polygon(hex,6,6,ability_value,ability_name);
})();
//绘制多边形能力图
function polygon(obj, side, part, ability_value, ability_name){
var ability = obj.getContext('2d');
ability.canvas.width = window.innerWidth*0.7;
ability.canvas.height = window.innerWidth*0.7;
var width = obj.width;
var height = obj.height;
var xCenter = width *0.5;
var yCenter = height *0.5;
var radius = width *0.3;
var space = radius/part;
var theta =Math.PI*2/side;
//绘制渐变多边形底层
for(varj=part;j>=1;j--){
ability.beginPath();
for(vari=0;i<=side;i++){
ability.lineTo(Math.cos(i*theta)*space*j+xCenter,-Math.sin(i*theta)*space*j+yCenter)
}
varr=73,g=101,b=115;
ability.fillStyle="rgba("+73+","+101+","+115+","+0.4+")";
ability.fill();
ability.closePath();
}
//绘制能力多边形
ability.beginPath();
for(vari=0;i<=side;i++){
varx=Math.cos(i*theta)*radius*ability_value[i%side]+xCenter;
vary= -Math.sin(i*theta)*radius*ability_value[i%side]+yCenter;
ability.lineTo(x,y);
}
ability.strokeStyle="rgba(255,255,96,1)";
ability.lineWidth=4;
ability.stroke();
ability.closePath();
//绘制字体for (var i=0; i
ability.fillStyle="rgba(0,0,0,1)";
ability.font="normal 15px Arial";
if(Math.cos(i*theta)*radius>0) {
varx=Math.cos(i*theta)*radius+3+xCenter;
vary= -Math.sin(i*theta)*radius*1.3+yCenter;
}else{
varx=Math.cos(i*theta)*radius*1.5+xCenter;
vary= -Math.sin(i*theta)*radius*1.3+yCenter;
}
ability.fillText(ability_name[i],x,y);
}
参考文献:http://www.codes51.com/article/detail_167821.html