美文网首页程序员JavaScript 进阶营
canvas笔记--圆形碰撞检测

canvas笔记--圆形碰撞检测

作者: _州舟_ | 来源:发表于2019-01-22 21:04 被阅读4次

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

未碰撞时这样子的

小球碰撞后小球变色

相关文章

网友评论

    本文标题:canvas笔记--圆形碰撞检测

    本文链接:https://www.haomeiwen.com/subject/xnvrjqtx.html