1. 圆形碰撞检测
// 弧度转角度
function d2a(n){
return n*Math.PI/180;
}
// 角度转弧度
function a2d(){
return n*180/Math.PI;
}
window.onload=function (){
let oC=document.getElementById('c1');
let gd=oC.getContext('2d');
let cx=400,cy=300,r=150;
gd.beginPath();
gd.arc(cx, cy, r, d2a(0), d2a(360), true);
gd.stroke();
oC.onmousemove=function (ev){
let x=ev.offsetX,y=ev.offsetY;
let dis=Math.sqrt(Math.pow(x-cx, 2)+Math.pow(y-cy, 2));
gd.clearRect(0, 0, oC.width, oC.height);
if(dis<=r){
gd.strokeStyle='red';
}else{
gd.strokeStyle='black';
}
gd.beginPath();
gd.arc(cx, cy, r, d2a(0), d2a(360), true);
gd.stroke();
};
};
正方形碰撞检测
let oc = document.querySelector("#c1")
//拿到画笔
let gd = oc.getContext('2d')
gd.strokeRect(100, 100, 200, 150)
oc.onmousemove = function (ev) {
let l = 100, t = 100, r = l + 200, b = t + 150
let x = ev.clientX-oc.offsetLeft, y = ev.clientY-oc.offsetTop
gd.clearRect(0, 0, oc.width, oc.height)
console.log(x,y)
if (l <= x && x <= r && t <= y && y <= b) {
gd.strokeStyle = 'red'
}else {
gd.strokeStyle = 'black'
}
gd.strokeRect(100, 100, 200, 150)
}