600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > JS实现图片旋转 前端实现图片旋转

JS实现图片旋转 前端实现图片旋转

时间:2021-10-14 13:18:59

相关推荐

JS实现图片旋转 前端实现图片旋转

非服务打开会有跨越问题

<!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.heightcanvas.height = img.width} else if(rotate > 225 && rotate <= 315) {// 270 宽高颠倒canvas.width = img.heightcanvas.height = img.width} else {canvas.width = img.widthcanvas.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>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。