在jQuery中将多个SVG图像转换为多个PNG图像

时间:2018-08-30 05:39:51

标签: java jquery html jquery-mobile

我将svg图像用作img src属性中的svg图像时遇到问题,并且必须通过jquery将多个svg图像转换为多个PNG图像

 <script src="http://d3js.org/d3.v3.js" charset="utf-8"></script>   
var doctype = '<?xml version="1.0" standalone="no"?>'
  + '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">';

// serialize our SVG XML to a string.
var source = (new XMLSerializer()).serializeToString(d3.select('svg').node());

// create a file blob of our SVG.
var blob = new Blob([ doctype + source], { type: 'image/svg+xml;charset=utf-8' });

var url = window.URL.createObjectURL(blob);

// Put the svg into an image tag so that the Canvas element can read it in.
var img = d3.select('body').append('img')
 .attr('width', 500)
 .attr('height', 500)
 .node();


img.onload = function(){
  // Now that the image has loaded, put the image into a canvas element.
  var canvas = d3.select('body').append('canvas').node();
  canvas.width = img.width/5;
  canvas.height = img.width/5;
  var ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0);
  var canvasUrl = canvas.toDataURL("image/png");
  var img2 = d3.select('body').append('img')
    .attr('width', 0)
    .attr('height', 0)
    .node();
  // this is now the base64 encoded version of our PNG! you could optionally 
  // redirect the user to download the PNG by sending them to the url with 
  // `window.location.href= canvasUrl`.
  img2.src = canvasUrl; 
   document.getElementById("upload-Preview").src = canvasUrl;
     
}
img.src = url;
var image = d3.select('body').append('img')
 .attr('width', 500)
 .attr('height', 500)
 .node();
image.onload=function(){
       // Now that the image has loaded, put the image into a canvas element.
  var canvas = d3.select('body').append('canvas').node();
  canvas.width = img.width/5;
  canvas.height = img.width/5;
  var ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0);
  var canvasUrl = canvas.toDataURL("image/png");
  var img2 = d3.select('body').append('img')
    .attr('width', 0)
    .attr('height', 0)
    .node();
  // this is now the base64 encoded version of our PNG! you could optionally 
  // redirect the user to download the PNG by sending them to the url with 
  // `window.location.href= canvasUrl`.
  img2.src = canvasUrl; 
      document.getElementById("upload-Preview1").src = canvas.toDataURL();
      
      function prepHref(linkElement) {
    var myDiv = document.getElementById('fullsized_image_holder');
    var myImage = myDiv.children[0];
    linkElement.href = myImage.src;
}
<img src="image.svg" class="svgimg">
<script src="http://d3js.org/d3.v3.js" charset="utf-8"></script>
<div id="fullsized_image_holder">Compress Img 1- <img id="upload-Preview" /></div>
<a href="#" onclick="prepHref(this)" download>Click here to download image</a>

0 个答案:

没有答案