麻烦老师检查,谢谢
来源:8-2 编程练习
qq_慕移动3101913
2020-03-03 15:05:08
<!DOCTYPE html> <html lang="en"> <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 context=canvas.getContext("2d"); //补充代码 //x,y位置 dir方向 isMouseInRect鼠标是否在矩形里面 var posx = 100, posy = 0, dir = 1, isMouseInRect = false; //鼠标移入,暂停动画 canvas.onmousemove = function(e){ var mouseX = e.offsetX; //获取鼠标x坐标 var mouseY = e.offsetY; //鼠标X坐标>左边界,<右边界 if(mouseX > posx && mouseX < posx +50 && mouseY > posy && mouseY < posy +50){ isMouseInRect = true; //鼠标在矩形里 }else{ isMouseInRect = false; //鼠标不在矩形里 } } //定时器 setInterval(function () { //鼠标移入,暂停动画 if(!isMouseInRect){ posy += 10 * dir; //移动位置和方向 } //清空画布 context.clearRect(0,0,canvas.width,canvas.height); context.fillStyle = 'rgb(0,128,0)'; //矩形颜色 context.fillRect(posx,posy,50,50); //填充矩形 if (posy + 50 >= canvas.height) { dir = -1 //反方向 }else if(posy <= 0){ dir = 1 //正方向 } },100); </script> </body> </html>
1回答
同学你好,代码是正确的,继续加油。祝学习愉快~