10分鐘,利用canvas畫一個小的loading界面
首先利用定義下canvas得樣式
<canvas width="1024" height="720" id="canvas" style="border: 1px solid #808080;display: block;margin: 100px auto;>你的游覽器不支持canvas</canvas>
這里主要要說的就是寬高,不要在style里面定義,不然會被拉伸。(對于這點,建議大家看下W3c文檔,不是很懂)
高度和寬度屬性確定畫布的寬度和高度的坐標系統(tǒng),而CSS屬性只確定大小的盒子,它會顯示。
var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d');
獲取對象,然后獲取上下文進行畫圖。
好的,接下來來個小例子(畫弧)
- //設置線寬,顏色(我喜歡通俗的稱他為空心畫法)
- ctx.lineWidth = 2;
- ctx.strokeStyle = '#176785';
//arc是花弧形,如果用fill的畫法的話,會把他封閉起來。 ctx.beginPath(); ctx.arc(512, 360, 100, 0.5 * Math.PI, 1 * Math.PI); ctx.stroke(); ctx.closePath();
對于ctx.beginPath();和 ctx.closePath();我覺得是canvas靈魂,一些好的canvas的引擎之所以效率高,他們有很大程度的關系。
1.比如,有些人畫的感覺畫出來的canvas是帶有鋸齒狀,就是在畫布上,繪制了同樣一件事情N次之后的效果。
看下面一個例子
ctx.beginPath(); ctx.arc(512, 360, 100, 0.5 * Math.PI, 1 * Math.PI); ctx.closePath(); ctx.stroke();
這就是ctx.closePath();的作用,閉合那些線,但是fill的畫法默認是帶有ctx.closePath();這個功能的,而ctx.beginPath();的作用就是相當于函數(shù)中的分割了,分割作用域。
2.例子就舉上面的,如果將上面兩段代碼何必,去掉ctx.beginPath();,那么那段弧形會被繪制兩次,而第二個則繪制一次。言下之意就是,假如沒有ctx.beginPath();的話,代碼中要繪制100個圖片,第一個就會繪制100次,第一個99次,總而言之是100+99+98+。。。。。
3.接下來兩個小例子。
//定義一個漸變的顏色,其實坐標,x,y,w,h var color = ctx.createLinearGradient(512, 460, 512, 260); // 開始顏色,和結束的顏色 color.addColorStop(0, '#499989'); color.addColorStop(1, '#176785'); ctx.beginPath(); ctx.fillStyle = color; ctx.arc(512, 360, 99, 0, 2 * Math.PI); ctx.fill(); ctx.closePath(); //繪制文本 var a = 12; ctx.font="50px Arial"; ctx.fillStyle = "#fff";
//居中 ctx.textAlign = "center"; ctx.beginPath(); //文字內(nèi)容, 起始坐標,寬度 ctx.fillText(a, 510, 375 , 64); ctx.closePath();
4.接下來我們把上面內(nèi)容結合起來。
//定時器 var timeClear; //定義一些數(shù)字 var arcNum = 0.02, textNum = 1; function load1(){ if(textNum >= 101){ return 0; } ctx.lineWidth = 2; ctx.strokeStyle = '#176785'; ctx.beginPath(); ctx.arc(512, 360, 100, (0.5 + arcNum - 0.02) * Math.PI, (0.5 + arcNum) * Math.PI); ctx.stroke(); ctx.closePath(); //繪制里面的漸變顏色 var color = ctx.createLinearGradient(512, 460, 512, 260); color.addColorStop(0, '#499989'); color.addColorStop(1, '#176785'); ctx.beginPath(); ctx.fillStyle = color; ctx.arc(512, 360, 99, (0.5 - arcNum/2)* Math.PI, (0.5 + arcNum/2) * Math.PI); ctx.fill(); ctx.closePath(); //繪制文本 ctx.font="80px Arial"; ctx.fillStyle = "#fff"; ctx.textAlign = "center"; ctx.beginPath(); ctx.fillText(textNum, 510, 385 , 124); ctx.closePath(); //ctx.clearRect(0,0,1024,720); arcNum = arcNum + 0.02; textNum = textNum + 1; } timeClear = setInterval(load1, 60);
看起來不太舒服,建議自己在電腦上測試:
在線調(diào)試唯一地址:http://www.gbtags.com/gb/debug/7400a9ba-51a7-409b-b1f4-b01363b9c625.htm
一個簡單的loading寫完了,但是里面有很多問題,比如那個fill和text都是有部分重復的繪制,繪制了99次的,其實我主要 想用fill那個圓來取代每次畫好的文本還要clear。如果你把文字換種顏色可能明白我的意思了。然后這會導致底部繪制100次,導致底部出現(xiàn)鋸齒的樣 子。
而且,繪制圓放在前面,就是相當于clearRect的作用,去清除文字。
面對這個問題,不知道大家如何解決的。


浙公網(wǎng)安備 33010602011771號