canvas筆記--圓形碰撞檢測
<!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>
未碰撞時這樣子的

小球碰撞後小球變色
