非服务打开会有跨越问题
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片旋转</title>
</head>
<body>
<button onclick="clickRotateImg()">旋转</button>
<button onclick="clickSubmit()">提交</button>
<img src="" id="img-box" crossorigin="anonymous"/>
</body>
<script>
var temp_rotate = 0, temp_base64;
/**
* 旋转图片
* @param src 图片路径
* @param rotate 旋转角度
* @returns {Promise<base64>}
*/
function rotateImg(src, rotate, callback) {
var img = new Image();
img.src = src;
img.crossOrigin= 'anonymous';
img.onload = function() {
var canvas = document.createElement('canvas')
var context = canvas.getContext('2d')
if(rotate > 45 && rotate <= 135) { // 90 宽高颠倒
canvas.width = img.height
canvas.height = img.width
} else if(rotate > 225 && rotate <= 315) { // 270 宽高颠倒
canvas.width = img.height
canvas.height = img.width
} else {
canvas.width = img.width
canvas.height = img.height
}
context.clearRect(0, 0, canvas.width, canvas.height)
context.translate(canvas.width / 2, canvas.height / 2)
context.rotate(rotate * Math.PI / 180)
context.translate(-canvas.width / 2, -canvas.height / 2)
context.drawImage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.height / 2, img.width, img.height)
context.translate(canvas.width / 2, canvas.height / 2)
context.rotate(-rotate * Math.PI / 180)
context.translate(-canvas.width / 2, -canvas.height / 2)
context.restore()
var base64 = canvas.toDataURL('image/png')
callback(base64);
temp_base64 = base64.replace('data:image/png;base64,', '');
}
}
rotateImg("image/1.jpeg", temp_rotate, function(base64){
document.getElementById('img-box').src = base64;
});
/**
* 点击-旋转图片
*/
function clickRotateImg(){
if(temp_rotate >= 360){
temp_rotate = 0;
}
temp_rotate = temp_rotate + 90;
rotateImg("image/1.jpeg", temp_rotate, function(base64){
document.getElementById('img-box').src = base64;
});
}
/**
* 提交数据
*/
function clickSubmit(){
console.log('后台base64转图片:', temp_base64);
}
</script>
</html>