在Web开发中,您可能需要旋转图像,这在CSS中很容易做到。像这样的简单代码变换:rotate(90deg);。但是如果我们想用 JS 来做呢?
将图像绘制到浏览器环境中的画布上并旋转它。但在此之前,我们需要做一些数学运算来保持原始图像的长宽比。
假设我们已经加载了图像,计算旋转后的图像可以如下完成:
const { PI, sin, cos, abs } = Math; const angle = (degree * PI) / 180; const sinAngle = sin(angle); const cosAngle = cos(angle); const rotatedWidth = abs(imageWidth * cosAngle) abs(imageHeight * sinAngle); const rotatedHeight = abs(imageWidth * sinAngle) abs(imageHeight * cosAngle);
接下来,我们使用一些画布 API 来进行实际的旋转:
const canvas = document.createElement('canvas'); const { width: canvasWidth, height: canvasHeight } = canvas; const canvasCtx2D = canvas.getContext('2d'); canvasCtx2D.clearRect(0, 0, canvasWidth, canvasHeight); canvasCtx2D.translate(canvasWidth / 2, canvasHeight / 2); canvasCtx2D.rotate(angle); canvasCtx2D.drawImage( image, -imageWidth / 2, -imageHeight / 2, imageWidth, imageHeight, ); return canvas.toDataURL('image/png');
核心代码到位后,我们可以进行一些优化并编写专用的 React hook 来使用它:
import { useEffect, useRef, useState } from 'react'; type RotatedImage = { src: string; width: number; height: number; } | null; let canvas: HTMLCanvasElement | null = null; let canvasCtx2D: CanvasRenderingContext2D | null = null; const getRotatedImage = ( image: HTMLImageElement | null, rotation: number, ): RotatedImage => { canvas ??= document.createElement('canvas'); canvasCtx2D ??= canvas.getContext('2d'); if (!image || !canvasCtx2D) return null; const { width: imageWidth, height: imageHeight, currentSrc } = image; const degree = rotation % 360; if (!degree) { return { src: currentSrc, width: imageWidth, height: imageHeight, }; } const { PI, sin, cos, abs } = Math; const angle = (degree * PI) / 180; const sinAngle = sin(angle); const cosAngle = cos(angle); canvas.width = abs(imageWidth * cosAngle) abs(imageHeight * sinAngle); canvas.height = abs(imageWidth * sinAngle) abs(imageHeight * cosAngle); // The width and height of the canvas will be automatically rounded. const { width: canvasWidth, height: canvasHeight } = canvas; canvasCtx2D.clearRect(0, 0, canvasWidth, canvasHeight); canvasCtx2D.translate(canvasWidth / 2, canvasHeight / 2); canvasCtx2D.rotate(angle); canvasCtx2D.drawImage( image, -imageWidth / 2, -imageHeight / 2, imageWidth, imageHeight, ); const src = canvas.toDataURL('image/png'); canvas.width = 0; canvas.height = 0; return { src, width: canvasWidth, height: canvasHeight, }; }; const useRotateImage = (imageSrc: string, rotation?: number): RotatedImage => { const imageEle = useRef(null); const [rotatedImage, setRotatedImage] = useState (null); useEffect(() => { if (typeof rotation === 'number') { let currImage = imageEle.current; if (currImage?.currentSrc !== imageSrc) { currImage = new Image(); imageEle.current = currImage; currImage.src = imageSrc; } currImage.decode().then( () => setRotatedImage(getRotatedImage(currImage, rotation)), () => setRotatedImage(null), ); } }, [imageSrc, rotation]); return rotatedImage; }; export default useRotateImage;
这里我复用了同一个canvas元素,以减少重复创建。其次,需要注意的是,我在每次旋转后将其宽度和高度设置为0,以减少内存使用。对了,我还做了清理画布的操作。这是因为在HTML规范中当你修改画布的宽度和高度时(无论是否与之前相同)都会清除画布,这与canvasCtx2D.clearRect(0, 0, canvasWidth, canvasHeight)相同,这现代浏览器支持。
在useRotateImage中,我保留对图像元素的引用,并在image.decode()之后设置旋转图像状态,该状态在图像数据准备好后解析。
以下是一个在线用例:
如果您觉得这有帮助,请考虑 订阅我的时事通讯 以获取更多有关 Web 开发的有用文章和工具。感谢您的阅读!
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3