html5 canvas拓展clearRect()实现圆形区域清理

canvas提供的clearRect(x, y, width, height)方法只能清理出特定位置的矩形区域,以下代码则能实现对圆形区域的清

理,主要是利用计算圆周率时的方法,将整个圆切成一个一个细小的正方形,然后再通过clearRect(x, y, width, height)

方法将一个一个细小的正方形区域清理。

<!DOCTYPE html>
<html>
	<head>
		<style>
			canvas{ border:1px solid black;}
			body{ margin:0;padding:0;}
		</style>
	</head>
	<body>
		<canvas id="canvas" width="400" height="400"></canvas>
		<script>
			var canvas=document.getElementById('canvas');
			var context=canvas.getContext('2d');
			
			context.beginPath();
			context.fillStyle="blue";
			context.arc(200,200,100,0,360*Math.PI/180);
			context.fill();
			
			function clearArc(x,y,radius){//圆心(x,y),半径radius
				var calcWidth=radius-stepClear;
				var calcHeight=Math.sqrt(radius*radius-calcWidth*calcWidth);
				
				var posX=x-calcWidth;
				var posY=y-calcHeight;
				
				var widthX=2*calcWidth;
				var heightY=2*calcHeight;
				
				if(stepClear<=radius){
					context.clearRect(posX,posY,widthX,heightY);
					stepClear+=1;
					clearArc(x,y,radius);
				}
			}
			var stepClear=1;//别忘记这一步
			clearArc(210,230,50);
		</script>
	</body>
</html>
懒得复制黏贴的可以移步至此下载源文件

点击打开链接

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值