请问,我这么写哪里出了问题,以至于鼠标放上去并没有停止动画。
来源:8-1 Canvas动画
qq_断罪_0
2017-09-07 15:21:09
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvas动画</title>
<style>
canvas{background-color:lightblue;}
</style>
</head>
<body>
<canvas width="800px" height="800px" id="canvas">您的浏览器不支持canvas</canvas>
<script>
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
//补充代码
ctx.fillStyle="green";
var posx=0,posy=0,dir=1,isMouseInRect=false;
canvas.onmousemove = function(e){
var mouseX = e.offsetX;
var mouseY = e.offsetY;
if(mouseX> posx && mouseX<posx+ 50 &&mouseY> posy && mouseY<posy+ 50){isMouseInRect = true;
}else{
isMouseInRect = false;
}
};
setInterval(function(){
if(!isMouseInRect){
posy=posy+10*dir;
}
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillRect(posx+100,posy,50,50);
if(posy+50>=canvas.height){
dir = -1;
}else if(posy<=0){
dir = 1;
}
},50)
</script>
</body>
</html>
1回答
怎么都被占用了呢
2017-09-07
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvas动画</title>
<style>
*{
margin:0;
padding: 0;
}
canvas{background-color:lightblue;}
</style>
</head>
<body>
<canvas width="800px" height="800px" id="canvas">您的浏览器不支持canvas</canvas>
<script>
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var timer=null;
//补充代码
ctx.fillStyle="green";
var posx=0,posy=0,dir=1,isMouseInRect=false;
canvas.onmousemove = function(e){
var mouseX = e.pageX;
var mouseY = e.pageY;
var chaX=Math.abs(mouseX-100);
var chaY=Math.abs(mouseY-posy);
if((chaX<50)&&(chaY<50)){
isMouseInRect=true;
}else{
isMouseInRect=false;
}
};
timer=setInterval(function(){
if(!isMouseInRect){
posy=posy+10*dir;
}
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillRect(posx+100,posy,50,50);
if(posy+50>=canvas.height){
dir = -1;
}else if(posy<=0){
dir = 1;
}
},50)
console.log(posy);
</script>
</body>
</html>
帮你完善了,请参考代码
相似问题