js+canvas鼠标悬停圆弧边框动态加载效果

鼠标悬停在div元素时,实现圆弧边框加载效果。

canvas-hover-circle.png

HTML代码:

<div class="btn">
	<canvas width="44" height="44" id="btn"></canvas>
</div>

CSS代码:

.btn {width:44px;height:44px;border-radius:50%;border:1px solid #f00;cursor:pointer;}
.ctxBtn canvas {position:absolute;left:0;top:0;width:100%;height:100%;}

js代码:

var	canvas, req, req2, color;	
function getObj(ojb, col){
	canvas = document.getElementById(ojb),
  	context = canvas.getContext('2d'),
  	center = canvas.width / 2,
  	rad = Math.PI * 2 / 100,
	speed = 4;
	color = col;
}
function drawFrame() {	
  	req = requestAnimationFrame(drawFrame);  		
  	context.clearRect(0, 0, canvas.width, canvas.height);
  	context.save();
  	context.beginPath();
  	context.strokeStyle = color;
  	context.lineWidth = 2;  	
  	context.arc(center, center, center -1, -Math.PI / 2, -Math.PI / 2 + speed * rad, false);
  	context.stroke();
  	context.restore();
  	if (speed < 40){
  		speed += 4;
  	}else{
  		speed = 40;
  	}
}
function canelDraw() {
	req2 = requestAnimationFrame(canelDraw);
	context.clearRect(0, 0, canvas.width, canvas.height);
	context.save();
  	context.beginPath();
  	context.strokeStyle = color;
  	context.lineWidth = 2;  	
  	context.arc(center, center, center -1, -Math.PI / 2, -Math.PI / 2 + speed * rad, false);
  	context.stroke();
  	context.restore();
	if (speed > 0){
  		speed -= 4;
  	}else{
  		speed = 0;
  	}
}

调用代码:

$(function(){
	$('.btn').hover(function(){
		cancelAnimationFrame(req2);
		var _id = $(this).children().attr('id');	
		getObj(_id,'#000');
		drawFrame();
	},function(){
		cancelAnimationFrame(req);
		canelDraw();
	});
});
关键词: Canvas