通过画布canvas实现图片缩放及旋转。
示例:示例
初始图片:
放大旋转后的图片
关键代码如下:
<div style="text-align: center;font-weight: bold;height: 20px;font-size: large;">
<button onclick="rotateImage()">旋转</button>
<button onclick="big()">放大</button>
<button onclick="small()">缩小</button>
</div>
<script type="text/javascript">
var scale = 1;
var rotation = 0; // 初始旋转角度为0
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
function drawImage(width,height) {
//设置 Canvas 大小为旋转缩放后的图片尺寸
canvas.width = width;
canvas.height = height;
// 清空 Canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 设置变换并绘制图片
ctx.translate(width / 2, height / 2);
ctx.rotate(rotation);
ctx.scale(scale, scale);
ctx.drawImage(image, -image.width / 2, -image.height / 2,image.width,image.height);
// 恢复 Canvas 变换状态
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
function rotateImage() {
rotation += Math.PI / 2; // 每次点击旋转90度
// 计算旋转后的图片尺寸
//旋转之后长宽变化
var rotatedWidth = scaledHeight;
var rotatedHeight = scaledWidth;
//更新旋转之后的全局长宽
scaledHeight = rotatedHeight;
scaledWidth = rotatedWidth;
drawImage(rotatedWidth,rotatedHeight);
}
function big() {
scale *= 1.1;
scaledWidth = scaledWidth * 1.1;
scaledHeight = scaledHeight * 1.1;
drawImage(scaledWidth,scaledHeight);
}
function small() {
scale /= 1.1;
scaledWidth = scaledWidth / 1.1;
scaledHeight = scaledHeight / 1.1;
canvas.width = scaledWidth;
canvas.height = scaledHeight;
drawImage(scaledWidth,scaledHeight);
}
</script>
完整代码: 源码