canvas 图片旋转 导出下载
Posted qiuxd
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了canvas 图片旋转 导出下载相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>picker</title> <style type="text/css"> * {margin: 0;padding: 0;} img {display: inline-block;height: auto;} canvas {position: fixed;top: -9999999px;left: -9999999px;} .img-wrap {text-align: center;padding: 50px 0;} .img-wrap img {width: 500px;} .btn {text-align: center;} .btn > button {margin-right: 20px;display: inline-block;} </style> </head> <body> <div id="app"> <canvas>系统版本太低</canvas> <div class="img-wrap"> <img id="t_img"> </div> <div class="btn"> <button type="button" onclick="changeDir(‘left‘)">往左旋转</button> <button type="button" onclick="changeDir(‘right‘)">往右旋转</button> <button type="button" onclick="down()">导出</button> </div> </div> </body> <script type="text/javascript"> var oc = document.querySelector(‘canvas‘); var ctx, image, xTimes = 0; var t_img = document.querySelector(‘#t_img‘); if (oc.getContext(‘2d‘)) { ctx = oc.getContext(‘2d‘); image = new Image(); image.src = ‘./img/cat.jpg‘; image.onload = function() { oc.width = image.width; oc.height = image.height; ctx.drawImage(this, 0, 0); t_img.src = oc.toDataURL(‘image/jpeg‘); } } function changeDir(_dir) { if (_dir === ‘left‘) { xTimes++; } else { xTimes--; } ctx.clearRect(0, 0, oc.width, oc.height); var temp = oc.width; oc.width = oc.height; oc.height = temp; var center = { x: Math.round(oc.width / 2), y: Math.round(oc.height / 2) }; console.log(center); ctx.translate(center.x, center.y); ctx.rotate(-90 * xTimes * Math.PI / 180); if (xTimes % 2 !== 0) { ctx.translate(-center.y, -center.x); } else { ctx.translate(-center.x, -center.y); } ctx.drawImage(image, 0, 0); t_img.src = oc.toDataURL(‘image/jpeg‘); } function down() { var aDom = document.createElement(‘a‘); aDom.download = "勒是一只猫"; aDom.href = oc.toDataURL(‘image/jpeg‘, 0.7); aDom.click(); } </script> </html>
以上是关于canvas 图片旋转 导出下载的主要内容,如果未能解决你的问题,请参考以下文章