【Canvas与艺术】绘制八一徽章
【图】
【代码】
<!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <head> <title>绘制八一徽章</title> <style type="text/css"> .centerlize{ margin:0 auto; width:1200px; } </style> </head> <body onload="init();"> <div class="centerlize"> <canvas id="myCanvas" width="12px" height="12px" style="border:1px dotted black;"> 如果看到这段文字说您的浏览器尚不支持HTML5 Canvas,请更换浏览器再试. </canvas> <img id="myImg" src="100.jpg" style="display:none;"/> </div> </body> </html> <script type="text/javascript"> <!-- /***************************************************************** * 将全体代码(从<!DOCTYPE到script>)拷贝下来,粘贴到文本编辑器中, * 另存为.html文件,再用chrome浏览器打开,就能看到实现效果。 ******************************************************************/ // canvas的绘图环境 var ctx; // 高宽 const WIDTH=512; const HEIGHT=512; // 舞台对象 var stage; //------------------------------- // 初始化 //------------------------------- function init(){ // 获得canvas对象 var canvas=document.getElementById('myCanvas'); canvas.width=WIDTH; canvas.height=HEIGHT; // 初始化canvas的绘图环境 ctx=canvas.getContext('2d'); ctx.translate(WIDTH/2,HEIGHT/2);// 原点平移到画布中央 // 准备 stage=new Stage(); stage.init(); // 开幕 animate(); } // 播放动画 function animate(){ stage.update(); stage.paintBg(ctx); stage.paintFg(ctx); // 循环 if(true){ window.requestAnimationFrame(animate); } } // 舞台类 function Stage(){ // 初始化 this.init=function(){ } // 更新 this.update=function(){ } // 画背景 this.paintBg=function(ctx){ // 清屏 ctx.clearRect(-WIDTH/2,-HEIGHT/2,WIDTH,HEIGHT); //黑底 ctx.fillStyle="black"; ctx.fillRect(-WIDTH/2,-HEIGHT/2,WIDTH,HEIGHT); // 黄圈 for(var i=0;i<5;i++){ var startAngle=i*Math.PI*2/5-Math.PI/2+Math.PI/24; var endAngle=startAngle+Math.PI*2/5-2*Math.PI/24; ctx.beginPath(); ctx.arc(0,0,200,startAngle,endAngle,false); ctx.lineWidth=30; ctx.strokeStyle="rgb(255,203,5)"; ctx.stroke(); } // 画黄五角星 draw5Star(ctx,0,0,190,"rgb(255,203,5)"); // 画红五角星 draw5Star(ctx,0,0,180,"rgb(218,37,30)"); // 写文字 ctx.fillStyle="rgb(255,203,5)"; ctx.font="64px 方正宋刻本秀楷简体"; ctx.textAlign="center"; ctx.textBaseLine="Middle"; ctx.fillText("八",0,0); ctx.fillText("一",0,50); } // 画前景 this.paintFg=function(ctx){ } } // 画实心五角星的函数 function draw5Star(ctx,x,y,r,color){ ctx.save() ctx.translate(x-r,y-r); ctx.beginPath(); ctx.moveTo(r, 0); ctx.lineTo(r+Math.cos(Math.PI*3/10)*r, r+Math.sin(Math.PI*3/10)*r); ctx.lineTo(r-Math.cos(Math.PI*1/10)*r, r-Math.sin(Math.PI*1/10)*r); ctx.lineTo(r+Math.cos(Math.PI*1/10)*r, r-Math.sin(Math.PI*1/10)*r); ctx.lineTo(r-Math.cos(Math.PI*3/10)*r, r+Math.sin(Math.PI*3/10)*r); ctx.lineTo(r, 0); ctx.closePath(); ctx.fillStyle=color; ctx.fill(); ctx.restore(); } /*--------------------------------------------- 凡是鼓励你做的事,那是有坑需要你去填; 凡是要你不惜代价的,那就是这个代价; 凡是禁止你做的事,那是有好处却不想分享给你; 凡是要你顾全大局的,你都不在这个“局”里。 ----------------------------------------------*/ //--> </script>
【原图】
END