svg图片代码data:image/svg+xml转png图片方法

把代码保存为html格式的文件中,用浏览器访问,即可右键保存
从AI软件或其它网站得到svg图片代码后,把他复制到下面源码上
注意:src=""图片地址中,一些参数的含义
d=‘这里是图片代码数据’
viewBox是图片显示区域,宽,高等
fill='%23000000’这里表示颜色 ,后面6位0表示黑色,只修改后6位即可
fill-opacity为1表示图片不透明.小数为透明.其它参数 不用修改

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>svg转png</title>
</head>
<body>
<img id="test" src="data:image/svg+xml;
utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' 
viewBox='0 0 555 344' width='555' 
height='344'%3E%3Cpath 
fill='%23000000' 
fill-opacity='1' 
d='M33.7 33.8v-7.5c0-8.2-3.8-11.7-8.1-11.7-6.7 0-8.9 3.5-8.9'
%3E%3C/path%3E%3C/svg%3E">

<p style="border:1px solid #ccc;color:red">
右键点击,图片另存为,png格式的
<img id="png"src=""href="" />
</p>

<script type="text/javascript">
  var test = document.getElementById('test');
  var svghtml = test.getAttribute('src');
var png = document.getElementById('png');
  var img = new Image();
  img.setAttribute('src', svghtml);
  img.onload = function () {
    var canvas = document.createElement('canvas');
    canvas.width = test.offsetWidth;
    canvas.height = test.offsetHeight;
    var context = canvas.getContext('2d');
    context.drawImage(img, 0, 0);
    var canvasData = canvas.toDataURL('image/png');
    var a = document.createElement('img');

      var img2 = document.createElement('img');
      img2.setAttribute('src', canvasData);
png.setAttribute('src', canvasData);
    //  img2.onload = function() {
      //  var a = document.createElement('a');
        // a.href = url;
     //   a.download = 'svg.png';
      //  a.href = img2.getAttribute('src');
       // a.click();
    //  }
    
  }
</script>
</body>
</html>

你可能感兴趣的:(css及js相关,svg图片代码转png)