上一篇講到用SVG製做loading動畫,其中提到了線性漸變在扇形區域中的問題,而且用SVG SIML語法制做的loading動畫並非全部瀏覽器都兼容,因此如今用Canvas從新實現了一遍。 canvas
這裏與SVG不一樣的是Canvas的動畫只能以腳本的方式進行,你們在用的時候稍微考慮一下性能問題,不過此版本基本若是瀏覽器版本不是過低的話應該都是兼容的,IE須要IE9以上的版本。瀏覽器
這裏的漸變不如SVG那麼好緣由就是上一講所提,不過還能夠接受,也沒什麼大的問題。性能
上代碼:動畫
圖片資源:this
樣式代碼:spa
.loadingcanvas-out
{width:70px;height:70px;margin:0 auto;position:absolute;left:50%;margin-left:-35px;top:55%;}
#loading-canvas
{border:0;position:relative;}圖片
HTML:資源
<div class="loadingcanvas-out">
<canvas id="loading-canvas"></canvas>
<img src="../images/gototop1.png" alt="加載中" style='position:absolute;top:0px;left:0px;z-index:99;width:70px;height:70px;' />
</div>get
腳本:it
var canvas = document.getElementById("loading-canvas"), index = 0;
var canvas = document.getElementById("loading-canvas"), index = 0;
function DrawSector(canvas_tag, start_angle, angle, radius, anticlockwise) {
var centerPoint = { x: 35, y: 35 };
start_angle = start_angle || 0;
if (canvas_tag.getContext) {
ctx = canvas_tag.getContext("2d");
ctx.translate(35, 35);
setInterval(
function() {
ctx.fillStyle = "White";
ctx.fill();
var g1 = ctx.createLinearGradient(0, 70, 60, 10);
g1.addColorStop(0, 'rgba(17,143,44,1)');
g1.addColorStop(0.5, 'rgba(137,215,1,0.4)');
g1.addColorStop(1, 'rgba(255,255,255,0.3)');
ctx.fillStyle = g1;
if (index >= 360) {
index = 0;
}
ctx.beginPath();
ctx.arc(0, 0, 33.9, 0, Math.PI / 180 * 150, false);
//畫出結束半徑
ctx.lineTo(0, 0);
ctx.closePath();
ctx.fill();
ctx.rotate(5 * Math.PI / 180);
index++;
}, 10);
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
//畫一個起始角度爲0度,結束角度爲150度,繪圖方向順時針的填充扇形
DrawSector(canvas, 0, Math.PI / 180 * 150, 35, false);
最終效果: