在慕課網看到一個canvas的課,感受很炫酷,就把它看完了,而後記下來。
http://www.imooc.com/learn/133git
拿小球來繪製具體的數字,具體的信息存儲在一個三維數組裏。具體繪製小球的代碼以下:canvas
function renderDigit(x,y,num,ctx) { ctx.fillStyle = '#3a48ab'; for(var i=0;i<digit[num].length;i++){ for(var j=0;j<digit[num][i].length;j++){ if(digit[num][i][j] === 1){ ctx.beginPath(); ctx.arc(x+2*j*(RADIUS+1)+(RADIUS+1),y+2*i*(RADIUS+1)+(RADIUS+1), RADIUS,0,2*Math.PI); ctx.closePath(); ctx.fill(); } } }
function render(ctx) { ctx.clearRect(0,0,WINDOW_WIDTH,WINDOW_HEIGH); var hours = parseInt(curShowTimeSeconds / 3600); var minutes = parseInt((curShowTimeSeconds - hours*3600) / 60); var seconds = curShowTimeSeconds % 60; renderDigit(MARGIN_LEFT,MARGIN_TOP,parseInt(hours/10),ctx); renderDigit(MARGIN_LEFT+15*(RADIUS+1),MARGIN_TOP,parseInt(hours%10),ctx); renderDigit(MARGIN_LEFT+30*(RADIUS+1),MARGIN_TOP,10,ctx); renderDigit(MARGIN_LEFT+39*(RADIUS+1),MARGIN_TOP,parseInt(minutes/10),ctx); renderDigit(MARGIN_LEFT+54*(RADIUS+1),MARGIN_TOP,parseInt(minutes%10),ctx); renderDigit(MARGIN_LEFT+69*(RADIUS+1),MARGIN_TOP,10,ctx); renderDigit(MARGIN_LEFT+78*(RADIUS+1),MARGIN_TOP,parseInt(seconds/10),ctx); renderDigit(MARGIN_LEFT+93*(RADIUS+1),MARGIN_TOP,parseInt(seconds%10),ctx); for (var i=0;i<balls.length;i++){ ctx.fillStyle = balls[i].color; ctx.beginPath(); ctx.arc(balls[i].x,balls[i].y,RADIUS,0,2*Math.PI,true); ctx.closePath(); ctx.fill(); } }
function updateBalls() { for(var i=0;i<balls.length;i++){ balls[i].x += balls[i].vx; balls[i].y += balls[i].vy; balls[i].vy += balls[i].g; if (balls[i].y >= WINDOW_HEIGH - RADIUS){ balls[i].y = WINDOW_HEIGH - RADIUS; balls[i].vy = -balls[i].vy*0.75; } } } function addBalls(x,y,num) { for(var i=0;i<digit[num].length;i++){ for(var j=0;j<digit[num][i].length;j++){ if(digit[num][i][j] === 1){ var aBall = { x:x+2*j*(RADIUS+1)+(RADIUS+1), y:y+2*i*(RADIUS+1)+(RADIUS+1), g:1.5+Math.random(), vx:Math.pow(-1,Math.ceil(Math.random()*1000))*4, vy:-5, color:colors[Math.floor(Math.random()*colors.length)] }; balls.push(aBall); } } } }