- <!DOCTYPE html>
- <HTML lang="zh">
- <head>
- <meta charset="UTF-8">
- <title>
- </title>
- <style>
- #mc { display: block; box-shadow: 0 0 10px black; margin: 0 auto; }
- </style>
- </head>
- <body>
- <canvas id="mc" width="1000px" height="600px">
- </canvas>
- <script>
- var mc = document.getElementById('mc');
- var ctx = mc.getContext('2d');
- var smallStyle = 'pink';
- function drawBig() {
- ctx.beginPath();
- ctx.fillStyle = 'orange';
- ctx.arc(500, 300, 100, 0, 2 * Math.PI);
- ctx.fill();
- }
- mc.onmousemove = function(ev) {
- // 清除画布
- ctx.clearRect(0, 0, 1000, 600);
- var e = ev || Windows.event;
- // 获取到鼠标的坐标
- var mx = e.offsetX;
- var my = e.offsetY;
- drawBig();
- // 绘制小球
- ctx.beginPath();
- ctx.arc(mx, my, 50, 0, 2 * Math.PI);
- ctx.fillStyle = smallStyle;
- ctx.fill();
- // 当圆心距小于半径之和时
- var dis = Math.sqrt(Math.pow(mx - 500, 2) + Math.pow(my - 300, 2));
- if (dis <= 150) {
- console.log(1);
- smallStyle = 'blue';
- } else {
- smallStyle = 'pink';
- }
- }
- </script>
- </body>
- </HTML>
未碰撞时这样子的
小球碰撞后小球变色
来源: http://www.jianshu.com/p/01955a902eb8