canva旋转图片 js_js 使用canvas 旋转 图片

最左边是原始图片,中间是canvas内容,右边是将canvas内容导出到img标签中

canvas绘图时,确定图片的原始尺寸,不是显示的dom大小,需要创建元素后获得

如果使用dom大小的话,会在绘制时只能绘制出一部分

canvas目前的感觉是分为绘图层和展示层

旋转和移动的是绘图层的中心

展示层呈现内容,大小也是展示层的大小

Title

.img {

width: 300px;

border: 1px solid black;

}

旋转

let degree = 0;

const sourceImg = document.getElementById('source');

const targetImg = document.getElementById('target');

const rotationCanvas = document.getElementById('rotationCanvas');

function getSize(url) {

return new Promise((resolve) => {

let img = document.createElement('img');

img.onload = () => {

resolve({

width: img.width,

height: img.height,

});

};

img.src = url;

});

}

async function rotation() {

let d = (degree * Math.PI) / 180;

degree += 30;

console.log(d);

let image = sourceImg;

let size = await getSize(sourceImg.src);

console.log('size', size);

const canvasWidth = size.width;

const canvasHeight = size.height;

rotationCanvas.width = canvasHeight;

rotationCanvas.height = canvasWidth;

let surfaceContext = rotationCanvas.getContext('2d');

surfaceContext.clearRect(0, 0, rotationCanvas.width, rotationCanvas.height);

surfaceContext.save();

// Translate to the center point of our image

surfaceContext.translate(canvasHeight * 0.5, canvasWidth * 0.5);

// Perform the rotation

surfaceContext.rotate(d);

// Translate back to the top left of our image

// surfaceContext.translate(-image.width * 0.5, -image.height * 0.5);

// Finally we draw the image

// surfaceContext.drawImage(image, -image.width * 0.5, -image.height * 0.5);

surfaceContext.drawImage(image, -canvasWidth / 2, -canvasHeight / 2);

// surfaceContext.drawImage(image, canvasWidth/2, canvasHeight/2);

// rotationCanvas.style.width = canvasHeight + 'px'

// rotationCanvas.style.height = canvasWidth + 'px'

surfaceContext.restore();

// surfaceContext.scale(.5, .5)

targetImg.src = rotationCanvas.toDataURL();

}

rotation();

function getBase64(img) {

console.log('img', img, canvasWidth, canvasHeight);

canvas.width = canvasWidth;

canvas.height = canvasHeight;

ctx.drawImage(img, 0, 0, img.width, img.height);

return canvas.toDataURL();

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值