今天小編和大家講講有關(guān)于:“如何在html5中通過(guò)cavas畫(huà)一面國(guó)旗?”這個(gè)問(wèn)題,下面是小編整理的繪畫(huà)方法!
具體代碼如下所示:
var canvas = document.getElementById("canvas");//創(chuàng)建一個(gè)cavas畫(huà)板
var context = canvas.getContext('2d');//設(shè)置畫(huà)板屬性
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];//各個(gè)小五角星的x坐標(biāo)
var minY = [0.20, 0.30, 0.45, 0.55,0.60,0.60,0.50];//各個(gè)小五角星的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); // 畫(huà)小五角星
}
//繪制五角星
function create5star(context,sx,sy,radius,color,rotato){
context.save();
context.fillStyle=color;
context.translate(sx,sy);//移動(dòng)坐標(biāo)原點(diǎn)
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++){//畫(huà)五角星的五條邊
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中通過(guò)cavas畫(huà)一面國(guó)旗?”這個(gè)問(wèn)題的實(shí)現(xiàn)方法,希望對(duì)大家的學(xué)習(xí)有所幫助,對(duì)于html這門(mén)語(yǔ)言有感興趣的小伙伴們可以在W3Cschool中進(jìn)行學(xué)習(xí)和了解!