最终想要的结果
思路
1、移动画布中心点
ctx.translate(x,y);//设置画布上的(0,0)位置,也就是旋转的中心点
2、此时旋转画布,会以(x,y)为中心点
3、所以我们需要将图片中心点也转移到(x,y)
ctx.drawImage(img,-img.width/2,-img.height/2);//把图片绘制在旋转的中心点,
4、旋转角度
ctx.rotate(90*Math.PI/180);
实现
function rotate90(imgUrl, type) {
return new Promise(function (resolve, reject) {
try {
// 1. 创建图片,canvas,获取画布
var img = new Image(),
canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
img.src = imgUrl;
// 2. 图片加载完成进行图片编辑
img.onload = function () {
// 2.1 设置canvas宽高,旋转90° ,宽高互换
canvas.width = this.height;
canvas.height = this.width;
// 2.2 画布中心点(也是起始点)平移至中心(0,0)->(x,y)
ctx.translate(canvas.width / 2, canvas.height / 2);
// 2.3 画布旋转90°
ctx.rotate(270 * Math.PI / 180);
// 2.4 绘制图像 图像起始点需偏移负宽高
ctx.drawImage(img, -this.width / 2, -this.height / 2);
// 2.5返回结果(base64)
resolve(canvas.toDataURL(type));
};
} catch (error) {
reject(error);
}
});