<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
canvas{
border: 2px solid red;
}
</style>
<script type="text/javascript">
window.οnlοad=function(){
var hspeed1=6;
var vspeed1=6;
var hspeed2=6;
var vspeed2=6;
var x1=200;
var y1=0;
var x2=0;
var y2=100;
var rad=20;
var timer1=null;
var timer2=null;
var txt=document.getElementById("canvas").getContext("2d");
document.getElementById("btn").οnclick=function(){
clearInterval(timer1);
clearInterval(timer2);
timer1=setInterval(function(){
txt.clearRect(0,0,400,400)
x1+=hspeed1;
y1+=vspeed1;
txt.beginPath()
txt.fillStyle="rgb(21,122,222)";
txt.arc(x1,y1,rad,0,2*Math.PI,true);
txt.closePath();
txt.fill();
if(x1>=395){
hspeed1=-hspeed1;
}
if(y1>=395){
vspeed1=-vspeed1;
}
if(x1<=5){
hspeed1=-vspeed1;
}
if(y1<=5){
vspeed1=-vspeed1;
}
},100);
timer2=setInterval(function(){
x2+=hspeed2;
y2+=vspeed2;
txt.beginPath();
txt.fillStyle="rgb(22,22,123)";
txt.arc(x2,y2,rad,0,2*Math.PI,true);
txt.closePath();
txt.fill();
if(x2>=395){
hspeed2=-hspeed2;
}
if(y2>=395){
vspeed2=-vspeed2;
}
if(x2<=5){
hspeed2=-hspeed2;
}
if(y2<=5){
vspeed2=-vspeed2;
}
},100)
}
document.getElementById("stop").οnclick=function(){
clearInterval(timer1);
clearInterval(timer2);
}
}
</script>
</head>
<body>
<canvas width="400px" height="400" id="canvas"></canvas>
<input type="button" id="btn" value="开始运动">
<input type="button" id="stop" value="停止运动">
</body>
</html>