实现图片旋转js
使用CSS transform属性旋转图片
通过CSS的transform属性可以轻松实现图片旋转效果。将rotate()函数与角度值结合,例如rotate(45deg)表示顺时针旋转45度。
const image = document.getElementById('myImage');
image.style.transform = 'rotate(45deg)'; // 旋转45度
动态旋转可通过修改角度值实现,例如结合用户输入或动画:

let angle = 0;
setInterval(() => {
angle += 1;
image.style.transform = `rotate(${angle}deg)`;
}, 50);
使用Canvas API旋转图片
Canvas的rotate()方法需配合translate()调整旋转中心点,避免图片偏离。

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.src = 'image.jpg';
img.onload = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2); // 设置旋转中心
ctx.rotate(Math.PI / 4); // 旋转45度(弧度制)
ctx.drawImage(img, -img.width / 2, -img.width / 2); // 调整绘制位置
ctx.restore();
};
使用requestAnimationFrame实现平滑动画
结合requestAnimationFrame实现高性能旋转动画:
function animate() {
angle = (angle + 1) % 360;
image.style.transform = `rotate(${angle}deg)`;
requestAnimationFrame(animate);
}
animate();
响应交互事件旋转图片
通过监听鼠标或触摸事件动态控制旋转:
let isDragging = false;
image.addEventListener('mousedown', () => isDragging = true);
document.addEventListener('mouseup', () => isDragging = false);
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const rect = image.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
const angle = Math.atan2(e.clientY - centerY, e.clientX - centerX) * 180 / Math.PI;
image.style.transform = `rotate(${angle}deg)`;
});
注意事项
- 性能优化:频繁操作DOM或Canvas时,使用
requestAnimationFrame避免卡顿。 - 单位选择:CSS使用角度(
deg),Canvas使用弧度(rad)。 - 兼容性:CSS变换和Canvas API均支持现代浏览器,无需额外库。
以上方法覆盖静态旋转、动态动画及交互式旋转场景,可根据需求选择实现方式。






