简体   繁体   中英

SVG to PNG in javascript

I have a problem with converting svg to png(base64). Svg to base64 works fine, because it displays just fine in the browser. But when i try to load in the image, it won't load. Anybody might have an idea why?

  var xml = new XMLSerializer().serializeToString(svg);
  var svg64 = btoa(xml);
  var b64start = 'data:image/svg+xml;base64,';
  var image64 = b64start + svg64;
  console.log(image64);

  const img = new Image();

  img.onload = function() {
    const canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);
    const dataBase64 = canvas.toDataURL('image/png');
    console.log(dataBase64);

    generatePowerpoint(response, dataBase64);
  }
  img.onerror = function() {
    console.log(this.src);

  }
  img.src = image64;

It depends of the browser you are using. Using Firefox, the svg tag must have width and height attributes (unit not in %).

It also depends of the content of the svg. If the svg contains non-latin characters, btoa may fail (even if it seems not to be the problem here since Svg to base64 works fine in your case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM