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>
相关推荐
大地飞鸿 2020-11-12
星星有所不知 2020-10-12
jinxiutong 2020-07-26
MIKUScallion 2020-07-05
songfens 2020-07-05
songfens 2020-06-11
songfens 2020-06-08
northwindx 2020-05-31
northwindx 2020-05-31
northwindx 2020-05-27
northwindx 2020-05-25
MIKUScallion 2020-05-25
jinxiutong 2020-05-10
xdyangxiaoromg 2020-05-10
大地飞鸿 2020-05-06
northwindx 2020-04-25
jinxiutong 2020-04-23