问题:实现一个鼠标移到矩形内则边框变红,鼠标离开矩形边框变回之前的形态的效果?


思路: 鼠标移动的事件中,获取距离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){

本文介绍了如何使用canvas进行矩形碰撞检测,通过监听鼠标移动事件,计算鼠标相对于canvas的距离,并判断是否在矩形区域内,以此实现鼠标移入边框变红、移出恢复的效果。
最低0.47元/天 解锁文章
3万+

被折叠的 条评论
为什么被折叠?



