canvas画布旋转问题

先说一下为什么要旋转的目的:因为在画布上签名,在不同的设备上我需要不同方向的签名图片,电脑是横屏,手机就是竖屏,所以需要把手机的签名旋转270°,因此写了这个方法。

关于画布旋转的重点就是获取到你的画布元素在 onload 函数里面调用图片旋转的方法

里面的methods.imageRotate就是旋转方法,只是基于vue3写的所以有methods

 $("#file").attr("src", canvas.value.toDataURL("image/png"));
    const fileImg = document.getElementById("file")
    fileImg.onload = function () {
     const imgValue = methods.imageRotate(fileImg, 270)
      // console.log("imgValue", imgValue)
      }

图片旋转的封装方法

//图片旋转
                imageRotate(img, rotate) {
                    let canvas = document.createElement("canvas");
                    let ctx = canvas.getContext("2d");
                    switch (rotate) {
                        case 90: // 旋转90°
                            canvas.width = img.height;
                            canvas.height = img.width;
                            ctx.rotate((90 * Math.PI) / 180);
                            ctx.drawImage(img, 0, -img.height, img.width, img.height);
                            break;
                        case 180: // 旋转180°
                            canvas.width = img.width;
                            canvas.height = img.height;
                            ctx.rotate((180 * Math.PI) / 180);
                            ctx.drawImage(img, -img.width, -img.height, img.width, img.height);
                            break;
                        case 270: // 旋转270°
                            canvas.width = img.height;
                            canvas.height = img.width;
                            ctx.rotate((-90 * Math.PI) / 180);
                            ctx.drawImage(img, -img.width, 0, img.width, img.height);
                            break;
                        default:
                            canvas.width = img.width;
                            canvas.height = img.height;
                            ctx.drawImage(img, 0, 0, img.width, img.height);
                            break;
                    }
                    return canvas.toDataURL("image/png");
                },

注:改方法并不会改变画布上的内容,是新建了一个变量来存储。

        *   千万记住要在onload调用

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值