代码如下:

<!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>

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

最新文章

  1. WordPress网站搭建
  2. [IOS8兼容性]IOS8上收不到通知
  3. 网页兼容浏览器测试工具Multibrowser
  4. CUBRID学习笔记 4 端口和win7下连接数据库cubrid教程
  5. ubuntu linux 使用常见问题
  6. JS瀑布流布局模式(1)
  7. HighCharts学习笔记
  8. (转)ie浏览器判断
  9. DataGridView 添加行 分类: DataGridView 2014-12-07 08:49 263人阅读 评论(0) 收藏
  10. NYOJ116 士兵杀敌(二)
  11. Window window = Window.GetWindow(控件)
  12. MySQL/MariaDB 在插入数据的时候提示 Incorrect string value
  13. docker 安装kafka
  14. mybatis学习1
  15. Rocket.Chat 开源IM系统部署
  16. 获取sevlet response值
  17. 走进APICloud的世界 (1)
  18. c基础_笔记_1
  19. 解决错误:Couldn&#39;t open file /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
  20. ubuntu 安装php-redis

热门文章

  1. 机器人学 —— 机器人感知(Kalman Filter)
  2. Redhat6下安装QEMU
  3. Ext的正则表达式
  4. 如何创建PostgreSQL数据库
  5. 6.cadence原理图下[原创]
  6. NDK(5) Android JNI官方综合教程[JavaVM and JNIEnv,Threads ,jclass, jmethodID, and jfieldID,UTF-8 and UTF-16 Strings,Exceptions,Native Libraries等等]
  7. UVA 11427 Expect the Expected (期望)
  8. [POJ1050]To the Max(最大子矩阵,DP)
  9. leetcode:Sort List(一个链表的归并排序)
  10. 《OD学hadoop》第二周0702