js实现图片360°旋转
时间: 2024-10-18 11:18:48 浏览: 17
在JavaScript中实现图片360°旋转通常需要结合CSS动画和HTML5的`<canvas>`元素。这里是一个简单的步骤:
1. **HTML结构**:
```html
<img id="image" src="your-image.jpg">
<canvas id="canvas"></canvas>
```
2. **JavaScript处理**:
```javascript
const img = document.getElementById('image');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 图片尺寸
let imgWidth = img.width;
let imgHeight = img.height;
// 创建一个新的canvas元素,用于旋转后的图像
const rotatedCanvas = document.createElement('canvas');
rotatedCanvas.width = imgWidth * 2;
rotatedCanvas.height = imgHeight * 2;
const rotatedCtx = rotatedCanvas.getContext('2d');
function drawRotatedImage() {
// 清空旋转后的canvas
rotatedCtx.clearRect(0, 0, rotatedCanvas.width, rotatedCanvas.height);
// 将原图绘制到中间位置,然后旋转
rotatedCtx.translate(imgWidth, imgHeight); // 移动到中心点
rotatedCtx.rotate(Math.PI / 180 * 360); // 旋转360度
rotatedCtx.drawImage(img, -imgWidth, -imgHeight); // 负号表示在中心画图
// 将旋转后的图像复制回原本的canvas
ctx.drawImage(rotatedCanvas, 0, 0);
}
// 触发旋转
setInterval(drawRotatedImage, 10); // 每隔10毫秒更新一次
```
阅读全文