JavaScript实现图片旋转及缩放(通过canvas)

通过画布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>

完整代码: 源码

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值