一、环境准备
在开始之前,请确保您的开发环境中已安装以下内容:
- PHP 7.0 或更高版本
- HTML5 支持
- CSS3 支持
二、基础图片移动
2.1 创建HTML结构
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>图片移动示例</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="800" height="600"></canvas>
<script src="script.js"></script>
</body>
</html>
2.2 编写JavaScript代码
// script.js
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 加载图片
const img = new Image();
img.src = 'path/to/your/image.jpg';
img.onload = function() {
// 设置图片初始位置
let x = canvas.width / 2;
let y = canvas.height / 2;
let dx = 2;
let dy = 2;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, x, y);
x += dx;
y += dy;
// 当图片移动到画布边缘时,改变方向
if (x + img.width > canvas.width || x < 0) {
dx = -dx;
}
if (y + img.height > canvas.height || y < 0) {
dy = -dy;
}
requestAnimationFrame(draw);
}
draw();
};
2.3 图片移动效果
三、高级技巧
3.1 支持多种图片移动模式
// 在draw函数中添加以下代码
function changeDirection(x, y, width, height) {
if (x + width > canvas.width || x < 0) {
dx = -dx;
}
if (y + height > canvas.height || y < 0) {
dy = -dy;
}
}
3.2 动态调整图片大小
// 在img.onload函数中添加以下代码
const scale = Math.min(canvas.width / img.width, canvas.height / img.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);