<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Transformers</title>
<style>
body {
background-color: #1c1b29;
}
#canvas {
margin: auto;
display: block;
border-radius: 12px;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="600"></canvas>
<!-- <script src="./transformer.js"></script> -->
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// 图片资源以及宽高
const imageSrc = "./imgs/bee.jpg"; //替换成你的图片
const imgWidth = 600;
const imgHeight = 848;
// 定义初始坐标和变化值
let x = -100;
let y = -150;
let dx = 4;
let dy = 3;
// 创建 Image 对象并注册 onload 方法
const imageObj = new Image();
imageObj.onload = function () {
animate();
};
imageObj.src = imageSrc;
function animate() {
// 清除画布,在下一帧重新绘制图像
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 执行变形效果,让图片来回反弹运动
if (x + dx > (imgWidth / -4) && x + dx < (imgWidth / 3)) {
x += dx;
} else {
dx = -dx;
x += dx;
}
if (y + dy > (imgHeight / -3) && y + dy < (imgHeight / 2)) {
y += dy;
} else {
dy = -dy;
y += dy;
}
// 绘制图片
ctx.drawImage(imageObj, x, y);
// 请求下一次动画帧绘制效果
requestAnimationFrame(animate);
}
</script>
</body>
</html>
The above is all the codes to implement js+canvas to realize the floating of cartoon characters on the page