在JavaScript中实现图片的90度旋转,可以通过操作HTML5的<canvas>
元素来完成。以下是基础概念及相关步骤:
<canvas>
元素上。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rotate Image 90 Degrees</title>
</head>
<body>
<input type="file" id="imageUpload" accept="image/*">
<canvas id="canvas" style="display: none;"></canvas>
<img id="rotatedImage" alt="Rotated Image">
<script>
document.getElementById('imageUpload').addEventListener('change', function(event) {
const file = event.target.files[0];
const img = new Image();
img.onload = function() {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Set canvas dimensions to the original image's dimensions
canvas.width = img.height;
canvas.height = img.width;
// Rotate the canvas context
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(Math.PI / 2);
ctx.translate(-img.width / 2, -img.height / 2);
// Draw the image onto the rotated canvas
ctx.drawImage(img, 0, 0);
// Convert the canvas back to an image
const rotatedImage = document.getElementById('rotatedImage');
rotatedImage.src = canvas.toDataURL();
rotatedImage.style.display = 'block';
};
img.src = URL.createObjectURL(file);
});
</script>
</body>
</html>
ctx.rotate(Math.PI / 2)
实现90度旋转,注意旋转中心点的调整。toDataURL()
方法导出为新的图片。通过上述方法,你可以轻松实现JavaScript中图片的90度旋转功能。
领取专属 10元无门槛券
手把手带您无忧上云