問題:實現一個鼠標移到矩形內則邊框變紅,鼠標離開矩形邊框變回之前的形態的效果?
思路: 鼠標移動的事件中,獲取距離context的左邊和上邊的距離,ev.offsetX; ev.offsetY,只要判斷這個範圍在矩形範圍內即可。
代碼實現:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
body {background:black; text-align: center;}
#c1 {background:white;}
</style>
<script>
window.onload=function (){
let oC=document.getElementById('c1');
let gd=oC.getContext('2d');
let l=50, t=50, w=100, h=70;
gd.strokeRect(l, t, w, h);
oC.onmousemove=function (ev){
gd.clearRect(0,0,oC.width,oC.height);
if(
ev.offsetX>=l &&
ev.offsetX<=l+w &&
ev.offsetY>=t &&
ev.offsetY<=t+h
){
gd.strokeStyle='red';
gd.strokeRect(l, t, w, h);
}else{
gd.strokeStyle='black';
gd.strokeRect(l, t, w, h);
}
};
};
</script>
</head>
<body>
<canvas id="c1" width="800" height="600"></canvas>
</body>
</html>