步骤,首先通过canvas绘制图形,然后进行设置
var plane=document.getElementById('plane');
var hb = document.createElement("canvas")
var plane = document.getElementById("plane")
var stx = hb.getContext("2d")
var divx=0,divy=0,count=0,ax=0,ay=0 //为过渡做准备
plane.appendChild(hb)
hb.width = 40
hb.height = 40
hb.style.display = "flex"
hb.style.position = "absolute"
stx.fillStyle = "red"
stx.rect(0,0,40,40)
stx.stroke()
监听鼠标并获取鼠标坐标
window.addEventListener("mousemove",function(e){
divx = e.clientX-plane.offsetLeft-plane.clientWidth/2;
divy = e.clientY-plane.offsetTop-plane.clientHeight/2;
count = 0 //过渡
})
过渡实现 (ax和ay用于更新canvas位置,divx和divy用与获取当前鼠标位置,couny实现过渡)
function draw(){
if(count<100){
ax+=divx/100
ay+=divy/100
}
plane.style.left = ax +"px"
plane.style.top = ay +"px"
count++
console.log(divx,divy);
}
完整的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
height: 100vh;
background: linear-gradient(200deg,#005bea,#00c6fb);
}
#plane{
color: #fff;
position: absolute;
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div id="plane">
</div>
<script>
var plane=document.getElementById('plane');
var hb = document.createElement("canvas")
var plane = document.getElementById("plane")
var stx = hb.getContext("2d")
var divx=0,divy=0,count=0,ax=0,ay=0
plane.appendChild(hb)
hb.width = 40
hb.height = 40
hb.style.display = "flex"
hb.style.position = "absolute"
stx.fillStyle = "red"
stx.rect(0,0,40,40)
stx.stroke()
window.addEventListener("mousemove",function(e){
divx = e.clientX-plane.offsetLeft-plane.clientWidth/2;
divy = e.clientY-plane.offsetTop-plane.clientHeight/2;
count = 0
})
function draw(){
if(count<100){
ax+=divx/100
ay+=divy/100
}
plane.style.left = ax +"px"
plane.style.top = ay +"px"
count++
console.log(divx,divy);
}
setInterval(draw,1)
</script>
</body>
</html>