png/jpg转svg,并下载到本地 ,需要下载png/jpg就简单了
| <!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8"> |
| <title>Title</title> |
| <script src="https://www.qianduange.cn/upload/article/jquery.min.js&" alt="" style="width: 100px;" id="img"> |
| <br> |
| <br> |
| <br> |
| <p>转换为svg:</p> |
| <div id="container"> |
| </div> |
| <p> |
| <button type="button" id="download">下载svg</button> |
| </p> |
| </body> |
| </html> |
| <script> |
| const img = document.getElementById('img'); //获取图片 |
| var canvas = document.createElement("canvas"); //canvas |
| const width = img.width; //图片宽 |
| const height = img.height;//图片高 |
| canvas.width = width; |
| canvas.height = height; |
| var ctx = canvas.getContext("2d"); |
| ctx.drawImage(img, 0, 0, width, height); |
| var dataURL = canvas.toDataURL(); //canvas获取的base64格式 |
| |
| //svg 的dom节点(字符串) |
| var svgString = `<svg id="downloadSvg" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" |
| width="${width}px" height="${height}px" |
| viewBox="0 0 ${width} ${height}" enable-background="new 0 0 ${width} ${height}" xml:space="preserve"> |
| <image id="image0" width="${width}" height="${height}" x="0" y="0" href="${dataURL}"></image> |
| </svg>`; |
| |
| //把svg插入到页面中 |
| $('#container').append(svgString); |
| |
| //下载功能 |
| function download(arg) { |
| var blob = new Blob([arg], {type: 'image/svg'}); |
| var href = window.URL.createObjectURL(blob); |
| var a = document.createElement('a'); |
| a.href = href; |
| a.download = 'download.svg'; //设置下载svg的名称 |
| document.body.appendChild(a); |
| a.click(); |
| document.body.removeChild(a); |
| URL.revokeObjectURL(href); |
| } |
| |
| $("#download").click(function () { |
| download(document.querySelector('svg').outerHTML) |
| }) |
| </script> |
| |
复制