使用canvas画出满天繁星
生活随笔
收集整理的這篇文章主要介紹了
使用canvas画出满天繁星
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今天學習了h5中的canvas標簽,結合之前學習的畫星星的算法,畫出了滿天繁星的效果圖
下面是展示:
做這個比較難的是畫星星的算法,下面是幫助大家理解一個圖:
只需要找到上面的十個點(5個小圓的點和5個大圓的點)之間的規律,使用ctx.lineTo依次連接就OK了。
大圓和小圓的5個點之間的度數都相差72度。
cos和sin的值可以用Math.cos()和Math.sin()計算
然后下面是具體的代碼示例:
demo.html
<!DOCTYPE html> <html> <head lang="en"><meta charset="utf-8"><title></title> </head> <body><canvas id="canvas" style="border:1px solid #aaa;margin: 50px auto;display:block;"></canvas> <script type="text/javascript" src="star.js"></script> </body> </html>
star.js
// 畫星空 window.onload = function() {// 找到畫布var canvas = document.getElementById("canvas");// 定義畫布的長寬canvas.width = 1000;canvas.height = 800;// 上下文,用于繪制var context = canvas.getContext("2d");/*** [skyStyle description]* @type {[type]}* createRadialGradient是徑向漸變填充函數*createRadialGradient的參數*從左至右依次為:* x0,y0,r0:起點的位置(相對canvas畫布)和小圓的半徑* x1,y1,r1:擴散至的終點的位置和大圓的半徑*/var skyStyle = context.createRadialGradient(canvas.width/2,canvas.height,0,canvas.width/2,canvas.height,canvas.height);//添加顏色skyStyle.addColorStop(0.0,'#035');skyStyle.addColorStop(1.0,'black');//將skyStyle用于填充展示天空的背景色context.fillStyle = skyStyle;//繪制矩形背景context.fillRect(0,0,canvas.width,canvas.height);for (var i = 0; i < 200; i++) {var r = Math.random() * 5 + 5;var x = Math.random()*canvas.width;// 讓星星都在canvas畫布的上面65%的區域顯示var y = Math.random()*canvas.height*0.65;var a = Math.random()*360;drawStar(context, x, y, r, a);}};// 繪制五角星 // 改善后的drawStar使用了漸變色radialGrad(徑向漸變)讓天空的顏色更加逼真 /*** [drawStar description]* @param {[type]} cxt [description] 繪制的上下文環境* @param {[type]} r [description] 五角星內部小圓的半徑* @param {[type]} R [description] 五角星外部大圓的半徑* @param {[type]} x [description] 五角星在水平方向上的位移* @param {[type]} y [description] 五角星在豎直方向上的位移* @param {[type]} rot [description] 五角星的旋轉角度* @return {[type]} [description]*/ function drawStar(ctx, x, y, R, rot) {ctx.save();//與restore()一起出現,防止狀態影響其他的繪制//圖形變換ctx.translate(x,y);//偏移ctx.rotate(rot/180*Math.PI);//旋轉ctx.scale(R,R);//縮放比例startPath(ctx);//開始繪制ctx.fillStyle = "#fb3";//內部填充的顏色ctx.fill();//內部填充顏色ctx.restore();}/*** [startPath description]畫星星的具體算法* @param {[type]} ctx [description]* @return {[type]} [description]*/ function startPath (ctx) {ctx.beginPath();for( var i = 0; i < 5; i++) {ctx.lineTo(Math.cos((18 + i*72)/180*Math.PI),-Math.sin((18 + i*72)/180*Math.PI));ctx.lineTo(Math.cos((54 + i*72)/180*Math.PI) * 0.5,-Math.sin((54 + i*72)/180*Math.PI) * 0.5);}ctx.closePath(); }
總結
以上是生活随笔為你收集整理的使用canvas画出满天繁星的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为首部鸿蒙,华为首部鸿蒙手机P50来了
- 下一篇: Linux虚拟机在线添加GPT格式硬盘