canvas学习
小球边缘运动
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div{
width: 500px;
height: 400px;
margin-top: 20px;
margin-left: 20px;
border:1px solid #c3c3c3;
position: relative;
}
canvas{
position: absolute;
}
</style>
</head>
<body>
<div id="div">
<canvas id="canvs" width="40px" height="40px"></canvas>
</div>
<div>
<button onclick="yundong()">运动</button>
</div>
</body>
</html>
<script>
let canvas = document.getElementById("canvs");
// 创建画布
let ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(12,12,10,0,2*Math.PI)
ctx.fillStyle="navy"
ctx.fill()
canvas.style.top=-10+'px'
canvas.style.left=-10+'px'
ctx.stroke()
// 点击运动
function yundong () {
let div = document.getElementById('div')
let width = div.offsetWidth;
let height = div.offsetHeight;
let left = div.offsetLeft;
console.log(width,height,left)
let num = -10
let timer = setInterval(function(){
num=num+1
canvas.style.top=num+'px'
console.log(num)
// 运动100px停止运动(根据实际控制)
if(num>100){
clearInterval(timer)
}
},50)
}
</script>
转一圈的代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div{
width: 300px;
height: 200px;
margin-top: 20px;
margin-left: 20px;
border:1px solid #c3c3c3;
position: relative;
margin-bottom: 100px;
}
canvas{
position: absolute;
}
</style>
</head>
<body>
<div id="div">
<canvas id="canvs" width="40px" height="40px"></canvas>
</div>
<div>
<button onclick="yundong()">运动</button>
</div>
</body>
</html>
<script>
let canvas = document.getElementById("canvs");
// 创建画布
let ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(12,12,10,0,2*Math.PI)
ctx.fillStyle="navy"
ctx.fill()
canvas.style.top=-10+'px'
canvas.style.left=-10+'px'
ctx.stroke()
let click = 0
function yundong () {
let div = document.getElementById('div')
let width = div.offsetWidth;
let height = div.offsetHeight;
let left = div.offsetLeft;
let top = div.offsetTop;
console.log(width,height,left,top)
let num = -10
let h1 = -10
let w2 = width-left/2
let h2 = height-top
if(click===1){
return
}
click=1
let timer = setInterval(function(){
num=num+1
canvas.style.left=num+'px'
if(num>width-left/2){
clearInterval(timer)
let timer1 = setInterval(function(){
h1=h1+1
canvas.style.top=h1+'px'
if(h1>height-top){
clearInterval(timer1)
let timer2 = setInterval(function(){
w2=w2-1
canvas.style.left=w2+'px'
if(w2<-10){
clearInterval(timer2)
let timer3 = setInterval(function(){
h2=h2-1
canvas.style.top=h2+'px'
if(h2<-10){
clearInterval(timer3)
let num = -10
let h1 = -10
let w2 = width-left/2
let h2 = height-top
click=0
}
},50)
}
},50)
}
},50)
}
},50)
console.log(num)
console.log(timer)
}
</script>
每天进步一点点