今天小編和大家講講有關(guān)于:“如何在html5中通過cavas畫一面國旗?”這個問題,下面是小編整理的繪畫方法!
具體代碼如下所示:
var canvas = document.getElementById("canvas");//創(chuàng)建一個cavas畫板
var context = canvas.getContext('2d');//設(shè)置畫板屬性
var width=canvas.width;
var height=width*2/3;
context.fillStyle="red";
context.fillRect(0,0,width,height);
var maxR = 0.15, minR = 0.05;
var maxX = 0.55, maxY = 0.35;//大五星的位置
var minX = [0.80, 0.90, 0.90, 0.80,0.65,0.50,0.40];//各個小五角星的x坐標(biāo)
var minY = [0.20, 0.30, 0.45, 0.55,0.60,0.60,0.50];//各個小五角星的y坐標(biāo)
var ox = height * maxX, oy = height * maxY;
html代碼:
<canvas id="canvas" width="600" height="400"></canvas>
js代碼:
create5star(context,ox,oy,height * maxR,"#ff0",0);//繪制大五角星
for (var idx = 0; idx < 7; idx++) {
var sx = minX[idx] * height, sy = minY[idx] * height;
var theta = Math.atan((oy - sy)/(ox - sx));
create5star(context,sx, sy, height * minR, "#ff0",-Math.PI/2+theta); // 畫小五角星
}
//繪制五角星
function create5star(context,sx,sy,radius,color,rotato){
context.save();
context.fillStyle=color;
context.translate(sx,sy);//移動坐標(biāo)原點
context.rotate(Math.PI+rotato);//旋轉(zhuǎn)
context.beginPath();//創(chuàng)建路徑
var x = Math.sin(0);
var y= Math.cos(0);
var dig = Math.PI/5 *4;
for(var i = 0;i< 5;i++){//畫五角星的五條邊
var x = Math.sin(i*dig);
var y = Math.cos(i*dig);
context.lineTo(x*radius,y*radius);
}
context.closePath();
context.stroke();
context.fill();
context.restore();
}
總結(jié)
以上所述的就是有關(guān)于:“如何在html5中通過cavas畫一面國旗?”這個問題的實現(xiàn)方法,希望對大家的學(xué)習(xí)有所幫助,對于html這門語言有感興趣的小伙伴們可以在W3Cschool中進行學(xué)習(xí)和了解!