Canvas实现圆圈移动

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="Justin">
  <meta name="Keywords" content="canvas">
  <meta name="Description" content="canvas study">
  <title>canvas_study</title>
 </head>
 <body>
 <div>
	<canvas id="test" width="600" height="600" 
          style="border:1px solid #000000;margin-left:300px"></canvas>
 </div>
 </body>
</html>
<script>
        //用于保存鼠标移动前的坐标
	var x=-100;
	var y=-100;
	//获取鼠标当前位置
	function mousePosition(ev){
	   if(ev.pageX || ev.pageY){
	     return {x:ev.pageX, y:ev.pageY};
	   }
	   return {
	     x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
	     y:ev.clientY + document.body.scrollTop - document.body.clientTop
	   };
	}
	document.onmousemove = mouseMove;
	
	var c=document.getElementById("test");
		var ctx=c.getContext("2d");
		//线
		ctx.moveTo(0,0);
		ctx.lineTo(600,600);
		ctx.moveTo(0,600);
		ctx.lineTo(600,0);
		ctx.stroke();
        //鼠标移动时执行
	function mouseMove(ev){
		 ev = ev || window.event;
		 var mousePos = mousePosition(ev);
		//清除上一个圆
		clear();
		
		
		var c=document.getElementById("test");
		var ctx=c.getContext("2d");

		//线
		ctx.moveTo(0,0);
		ctx.lineTo(600,600);
		ctx.moveTo(0,600);
		ctx.lineTo(600,0);
		ctx.stroke();
                //圆
		ctx.beginPath();
		ctx.arc(mousePos.x-300,mousePos.y,40,0,2*Math.PI);
		ctx.stroke();
		x=mousePos.x;
		y=mousePos.y;
	}

	function clear(){
		var c=document.getElementById("test");
		var ctx=c.getContext("2d");
		ctx.clearRect(0,0,600,600);
	}
	
</script>

发表评论

电子邮件地址不会被公开。 必填项已用*标注