Html5+JavaScript 在Canvas上绘制五星红旗,具体思路如下图所示:
绘制思路在上图中已有说明,具体代码如下:
1 <script type="text/javascript"> 2 3 //绘制五角星,其中一点垂直向上,相隔的点相连,即可绘制。 4 function drawStar(ctx,starCenterX,starCenterY,starRadius) { 5 var aX = starCenterX; 6 var aY = starCenterY - starRadius; 7 var bX = starCenterX - Math.cos(18 * Math.PI / 180) * starRadius; 8 var bY = starCenterY - Math.sin(18 * Math.PI / 180) * starRadius; 9 var cX = starCenterX - Math.cos(54 * Math.PI / 180) * starRadius; 10 var cY = starCenterY + Math.sin(54 * Math.PI / 180) * starRadius; 11 var dX = starCenterX + Math.cos(54 * Math.PI / 180) * starRadius; 12 var dY = starCenterY + Math.sin(54 * Math.PI / 180) * starRadius; 13 var eX = starCenterX + Math.cos(18 * Math.PI / 180) * starRadius; 14 var eY = starCenterY - Math.sin(18 * Math.PI / 180) * starRadius; 15 ctx.beginPath(); 16 ctx.fillStyle = "yellow"; 17 ctx.moveTo(aX, aY); 18 ctx.lineTo(cX, cY); 19 ctx.lineTo(eX, eY); 20 ctx.lineTo(bX, bY); 21 ctx.lineTo(dX, dY); 22 ctx.lineTo(aX, aY); 23 ctx.fill(); 24 ctx.closePath(); 25 } 26 27 window.onload = function () { 28 var c = document.getElementById("myCanvas"); 29 var ctx = c.getContext("2d"); 30 ctx.clearRect(0, 0, c.width, c.height); 31 var width = 300*1.5; 32 var height = 200*1.5; 33 var sX = 50; //其实坐标 34 var sY = 50; //其实坐标 35 var step = 10*1.5; 36 //绘制矩形 37 ctx.beginPath(); 38 ctx.lineWidth = 1; 39 ctx.fillStyle = "red"; 40 ctx.fillRect(sX, sY, width, height); 41 ctx.closePath(); 42 //绘制大五角星 43 var bigStarCenterX = sX + 5 * step; 44 var bigStarCenterY = sY + 5 * step; 45 var bigStarRadius = (height * 3 / 10) / 2; //外接圆直径为旗高3/10,半径要再除以2 46 drawStar(ctx, bigStarCenterX, bigStarCenterY, bigStarRadius); 47 //绘制小五角星 48 var smallStarRadius = (height * 1 / 10) / 2; //外接圆直径为旗高1/10,半径要再除以2 49 50 var smallStarCenterX_1 = sX + 10 * step; 51 var smallStarCenterY_1 = sY + 2 * step; 52 drawStar(ctx, smallStarCenterX_1, smallStarCenterY_1, smallStarRadius); 53 var smallStarCenterX_2 = sX + 12 * step; 54 var smallStarCenterY_2 = sY + 4 * step; 55 drawStar(ctx, smallStarCenterX_2, smallStarCenterY_2, smallStarRadius); 56 var smallStarCenterX_3 = sX + 12 * step; 57 var smallStarCenterY_3 = sY + 7 * step; 58 drawStar(ctx, smallStarCenterX_3, smallStarCenterY_3, smallStarRadius); 59 var smallStarCenterX_4 = sX + 10 * step; 60 var smallStarCenterY_4 = sY + 9 * step; 61 drawStar(ctx, smallStarCenterX_4, smallStarCenterY_4, smallStarRadius); 62 }; 63 </script>
时间: 2024-10-19 04:00:20