svgToImg.js 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. (function (global) {
  2. global.svgToImg = function (svgHtml) {
  3. this.svgHtml = svgHtml;
  4. };
  5. global.svgToImg.prototype = {
  6. /**
  7. * svg转图片
  8. * @description
  9. * 1.将svg转base64;
  10. * 2.将base64格式的svg转指定的图片格式并下载
  11. * @param fileName
  12. * 图片名称
  13. * @param imgType
  14. * 图片类型:jpg/png/bmp
  15. *
  16. */
  17. change: function (fileName, imgType) {
  18. var This = this;
  19. //1.给svg标签添加属性:version和xmlns
  20. [
  21. ['version', 1.1],
  22. ['xmlns', "http://www.w3.org/2000/svg"],
  23. ['fill','#000000']
  24. ].forEach(function (item) {
  25. This.svgHtml.setAttribute(item[0], item[1]);
  26. });
  27. // 2.获取到svg标签+标签内的所有元素
  28. var str = This.svgHtml.parentNode.innerHTML;
  29. //3.创建img
  30. var img = document.createElement('img');
  31. img.style.backgroundColor = '#fff';
  32. $(img).css({
  33. background: "#fff"
  34. });
  35. // 4.svg格式的base64图像
  36. img.setAttribute('src', 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(str))));
  37. //base64格式的svg
  38. //document.getElementById('baseSvg').src='data:image/svg+xml;base64,'+ btoa(unescape(encodeURIComponent(str)));
  39. // 5.转换成指定图片格式
  40. img.onload = function () {
  41. img.style.backgroundColor = '#fff';
  42. // 1.创建canvas
  43. var canvas = document.createElement('canvas');
  44. var context = canvas.getContext("2d");
  45. context.fillStyle = 'RGB(255, 0, 0)';
  46. canvas.width = img.width;
  47. canvas.height = img.height;
  48. // 2.根据base64格式的svg生成canvas
  49. context.drawImage(img, 0, 0);
  50. // 3.将canvas转字符串(按指定好的图片格式)
  51. var canvasData = canvas.toDataURL("image/" + imgType);
  52. // 4.创建图片元素
  53. var img2 = document.createElement('img');
  54. // 5.生成图片
  55. img2.setAttribute('src', canvasData);
  56. //$(img2).css({
  57. // background: "#fff"
  58. //});
  59. // 6.下载该图片
  60. img2.onload = function () {
  61. //console.log($(img2));
  62. var a = document.createElement("a");
  63. // 下载
  64. a.download = fileName + "." + imgType;
  65. a.href = img2.getAttribute('src');
  66. a.click();
  67. };
  68. };
  69. }
  70. }
  71. }(this));