js实现旋转90
实现旋转90度的JavaScript方法
在JavaScript中实现旋转90度可以通过多种方式完成,具体取决于旋转的对象类型(如图像、DOM元素、矩阵等)。以下是几种常见场景的实现方法:
旋转DOM元素90度
使用CSS的transform属性可以实现DOM元素的旋转:
const element = document.getElementById('myElement');
element.style.transform = 'rotate(90deg)';
若要动态切换旋转角度,可以结合CSS类或直接修改transform属性:

let rotation = 0;
function rotateElement() {
rotation += 90;
element.style.transform = `rotate(${rotation}deg)`;
}
旋转图像数据90度(Canvas)
通过Canvas处理图像数据的旋转:
function rotateImage90(image) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 交换宽高以适应旋转后的尺寸
canvas.width = image.height;
canvas.height = image.width;
// 平移并旋转画布
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(Math.PI / 2);
ctx.drawImage(image, -image.width / 2, -image.height / 2);
return canvas;
}
旋转二维数组(矩阵)90度
顺时针旋转二维数组(矩阵)90度的算法:

function rotateMatrix90(matrix) {
const n = matrix.length;
const rotated = Array.from({ length: n }, () => new Array(n));
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
rotated[j][n - 1 - i] = matrix[i][j];
}
}
return rotated;
}
示例输入和输出:
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(rotateMatrix90(matrix));
// 输出: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
使用CSS动画实现连续旋转
通过CSS动画实现元素的连续旋转效果:
const element = document.getElementById('myElement');
element.style.animation = 'spin 2s linear infinite';
// 在CSS中定义动画
// @keyframes spin {
// from { transform: rotate(0deg); }
// to { transform: rotate(360deg); }
// }
以上方法涵盖了从DOM操作到数据处理的不同场景,可根据实际需求选择合适的方式实现旋转功能。






