一个简单的实例

<head> <meta charset=”UTF-8″> <meta http-equiv=”X-UA-Compatible” content=”IE=edge”> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″> <title>手写签名2</title> <style> body { margin: 0; } #cvs { display: block; background-color: #dddddd; } .btn { position: absolute; top: 0; } .p2 { left: 50px } </style> </head> <body> <button class=”btn” onclick=”onRotate()”>旋转</button> <button class=”btn p2″ onclick=”onDownload()”>下载</button> <canvas id=”cvs” width=”400″ height=”300″></canvas> <script> const cvs = document.getElementById(‘cvs’) const ctx = cvs.getContext(‘2d’) let isDrawing = false const onRotate = () => { const { width, height } = cvs const img = new Image() img.src = cvs.toDataURL(‘image/png’) img.onload = () => { cvs.width = height cvs.height = width ctx.translate(cvs.width, 0) ctx.rotate(Math.PI / 180 * 90) ctx.drawImage(img, 0, 0) } } const onDownload = async () => { const a = document.createElement(‘a’) a.setAttribute(‘download’, ‘name.png’) const res = await fetch(cvs.toDataURL(‘image/png’)) const blob = await res.blob() a.href = URL.createObjectURL(blob) a.click() } const addEvents = (cvs, name, call) => { const isMobile = navigator.userAgent.match(/Mobile/) const mobileNameObj = { ‘mousedown’: ‘touchstart’, ‘mousemove’: ‘touchmove’, ‘mouseup’: ‘touchend’ } if (isMobile) { cvs.addEventListener(mobileNameObj[name], e => { call(e.touches[0]) }) } else { cvs.addEventListener(name, e => { call(e) }) } } addEvents(cvs, ‘mousedown’, e => { isDrawing = true ctx.moveTo(e.pageX, e.pageY) }) addEvents(cvs, ‘mousemove’, e => { if (isDrawing) { ctx.lineWidth = 5 ctx.lineTo(e.pageX, e.pageY) ctx.stroke() } }) addEvents(cvs, ‘mouseup’, e => { isDrawing = false }) </script> </body>

原文地址:http://www.cnblogs.com/Tanguncle/p/16928385.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性