canva旋转图片 js_js canvas 照片旋转 demo详解

照片旋转

1.jpg

var img = document.querySelector("img");

var canvas = document.querySelector("canvas");

var context = canvas.getContext('2d');

var imgHeight = 200;

var imgWidth = 200;

img.onload = function(){

imgHeight = img.height;

imgWidth = img.width;

}

function fileChangeEvent(file){

var URL = window.URL || window.webkitURL;

img.src = URL.createObjectURL(file);

img.onload = function(){

imgHeight = img.height;

imgWidth = img.width;

}

}

function rotate90()

{

img.style.width = "initial"; // 防止 css 导致旋转时的图片宽高比拉伸而导致的模糊问题

canvas.width = imgHeight;

canvas.height = imgWidth;

context.translate(canvas.width * 0.5, canvas.height * 0.5);

context.rotate(Math.PI * 0.5);

context.translate(-canvas.height * 0.5, -canvas.width * 0.5);

context.drawImage(img, 0, 0, imgWidth, imgHeight);

img.src = canvas.toDataURL("image/png");

}

function rotate180()

{

canvas.width = imgWidth;

canvas.height = imgHeight;

context.rotate(Math.PI);

context.translate(-canvas.width, -canvas.height);

context.drawImage(img, 0, 0, imgWidth, imgHeight);

img.src = canvas.toDataURL("image/png");

}

function rotate270()

{

img.style.width = "initial"; // 防止 css 导致旋转时的图片宽高比拉伸而导致的模糊问题

canvas.width = imgHeight;

canvas.height = imgWidth;

// 以中心点为基准旋转,所有的旋转只改变了 canvas 画笔的坐标轴,对画布没有任何影响

context.translate(canvas.width * 0.5, canvas.height * 0.5);

context.rotate(-Math.PI * 0.5);

context.translate(-canvas.height * 0.5, -canvas.width * 0.5);

context.drawImage(img, 0, 0, imgWidth, imgHeight);

img.src = canvas.toDataURL("image/png");

}

document.querySelectorAll("input[type='button']")[0].onclick = function(){

rotate90();

};

document.querySelectorAll("input[type='button']")[1].onclick = function(){

rotate180();

};

document.querySelectorAll("input[type='button']")[2].onclick = function(){

rotate270();

};

document.querySelectorAll("input[type='button']")[3].onclick = function(){

history.back();

};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值