美文网首页
div2svg2img2canvas2downloadFile

div2svg2img2canvas2downloadFile

作者: xueyueshuai | 来源:发表于2023-06-30 18:49 被阅读0次
    <template>
        <div id="container" style="width:200px;height: 200px">
          <div style="box-sizing:border-box;border:3px solid #000;width:200px;height: 200px;display: flex;justify-content: center;align-items: center;border-radius: 50%;background-color: #14ff14">
            <div style="width: 40px;height: 40px;background-color: #000;border-radius: 100%"></div>
          </div>
        </div>
    </template>
    
    <script>
    
    export default {
      name: '',
      data() {
        return {}
      },
      mounted() {
        this.svg2img()
      },
      methods: {
        getSvgStr() {
          let divContent = document.getElementById("container").innerHTML;
    
          let svg = 
            "<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
              "<foreignObject width='100%' height='100%'>" +
                "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:16px;font-family:Helvetica'>" +
                  divContent +
                "</div>" +
              "</foreignObject>" +
            "</svg>";
          return svg
        },
        svg2img() {
          // img
          let data = "data:image/svg+xml," + this.getSvgStr();
          let img = new Image();
          img.src = data;
          document.body.appendChild(img);
          
          // canvas
          let canvas = document.createElement('canvas');  //准备空画布
          canvas.width = img.width;
          canvas.height = img.height;
          let context = canvas.getContext('2d');  //取得画布的2d绘图上下文
          context.drawImage(img, 0, 0);
          document.body.appendChild(canvas);
    
          // 下载
          let a = document.createElement('a');
          a.href = canvas.toDataURL('image/png');  //将画布内的信息导出为png图片数据
          a.download = "img-demo";  //设定下载名称
          a.click();
        }
      }
    }
    </script>
    
    <style lang="scss" scoped>
    </style>
    
    

    相关文章

      网友评论

          本文标题:div2svg2img2canvas2downloadFile

          本文链接:https://www.haomeiwen.com/subject/oultudtx.html