爱程序网

html --- canvas --- javascript --- 拖拽圆圈

来源: 阅读:

代码如下:

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<canvas id="canvas">
    您的浏览器不支持canvas!
</canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 450;

function Circle(centreX, centreY, radius)
{
    this.centreX = centreX;
    this.centreY = centreY;
    this.radius  = radius;
}
Circle.prototype.paint = function(color){
    ctx.beginPath();
    ctx.arc(this.centreX, this.centreY, 
            color == COLOR0 ? this.radius + 1 : this.radius, 0, Math.PI*2, true);
    ctx.fillStyle = color;
    ctx.fill();
}
Circle.prototype.include = function(mouseX, mouseY){
    var distanceX = (mouseX - this.centreX) * (mouseX - this.centreX);
    var distanceY = (mouseX - this.centreY) * (mouseY - this.centreY);
    var distance = distanceX + distanceY;
    if(distance - this.radius * this.radius > 0)
        return false;
    else
        return true;
}

var COLOR0 = "white", COLOR1 = "lightblue";

Circle.prototype.move = function(moveX, moveY){
    circle.paint(COLOR0);
    circle.centreX = moveX;
    circle.centreY = moveY;
    circle.paint(COLOR1);
}
var circle = new Circle(canvas.width/2, canvas.height/2, 45);
circle.paint(COLOR1);

canvas.addEventListener("mousedown", onMouseDown, false);
canvas.addEventListener("mousemove", onMouseMove, false);
canvas.addEventListener("mouseup",   onMouseUp,   false);

var movable = false;

function onMouseDown(event){
    var mouseX = event.pageX - this.offsetLeft;
    var mouseY = event.pageY - this.offsetTop;
    if(circle.include(mouseX, mouseY))
        movable = true;
}

function onMouseMove(event){
    var mouseX = event.pageX - this.offsetLeft;
    var mouseY = event.pageY - this.offsetTop;
    if(movable){
        circle.move(mouseX, mouseY)
    }
}

function onMouseUp(event){
    movable = false;
}


</script>


</body>
</html>

 

 

 

 

下面的圆是可以拖拽的,运行结果如下:

 

 

 

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助