html5 Canvas 拖拽

源码


//获取到舞台
var canvas=document.getElementById("stage");
//舞台2d绘图接口
var context=canvas.getContext("2d");
//获取中心点置
var centerX=canvas.width/2;
var centerY=canvas.height/2;
             /**
              * 球对象
              
*/
             var Ball=function(x,y,radius,color)
             {
//球的中心点位置
this.x=x;
this.y=y;
//球的半径
this.radius=radius;
//球的颜色
this.color=color;
//球的边框颜色
context.strokeStyle = color;
//球体颜色
context.fillStyle=color; 
/**
  * 绘制球
  
*/ 
this.draw=function()
{
context.clearRect(0,0,centerX*2,centerY*2);
context.beginPath(); 
                     context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false); 
                     context.fill(); 
                     context.stroke();
                     context.closePath();
}
             } 
             //球的半径 
             var rd=20;
             //创建一个球对象,让球在马路的最左边
             var ball=new Ball(centerX*Math.random(),centerY*Math.random(),rd,"#ccc"); 
             //显示球
             ball.draw(); 
             canvas.addEventListener("mousedown",OnMouseDown,false);
             canvas.addEventListener("mousemove",OnMouseMove,false);
             canvas.addEventListener("mouseup",OnMouseUp,false);
             var isDown=false;
             function OnMouseDown(evt)
             {

var mouseX=evt.layerX;
                 var mouseY=evt.layerY;
                 var dx=mouseX-ball.x;
                 var dy=mouseY-ball.y;
                 //计算从圆心到鼠标点击的距离
var len=Math.sqrt(dx*dx+dy*dy);
if(Math.abs(len)<=rd)
{
isDown=true;

else
{
isDown=false;
}
             }
             function OnMouseMove(evt)
             {
if(isDown)
{
var mouseX=evt.layerX;
var mouseY=evt.layerY;
ball.x=mouseX;
ball.y=mouseY;
ball.draw(); 
}
             }
             function OnMouseUp(evt)
             {
isDown=false;

             } 

 作者:Louja

出处:http://loujady.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此声明,且在文章页面给出原文连接,否则保留追究法律责任的权利。 

 

原文地址:http://www.cnblogs.com/loujady/archive/2011/12/10/2283272.html

0 个评论

要回复文章请先登录注册