前端生成海报

前端截图 前端生成海报 保存图片

  • 内容为div
  • 通过html2canvas截图 生成Bob | base64
  • 保存到本地(下载方法无法下载,生成图片长按保存到本地)
  • style

          * {
              margin: 0;
              padding: 0;
              list-style: none;
          }
    
          .view {
              width: 375px;
              height: 667px;
              position: relative;
              color: #FFFFFF;
              text-align: center;
              font-size: 20px;
              background: #409EFF;
          }
    
          .title {
              width: 100%;
              font-size: 30px;
              position: absolute;
              top: 50px;
              left: 50%;
              transform: translateX(-50%);
          }
    
          .content {
              width: 100%;
              font-size: 16px;
              position: absolute;
              top: 100px;
              left: 50%;
              transform: translateX(-50%);
          }
    
          .result {
              width: 375px;
              height: 667px;
          }
    
          .result>img {
              width: 100%;
              height: 100%;
          }
    
          .btn {
              padding: 10px;
          }
    
          button {
              padding: 6px 10px;
          }
    

    html

      
    海报标题
    海报内容


    js

    //        
    function saveFile() {
              let dpi = window.devicePixelRatio || 2
              let options = {
                  useCORS: true,
                  ignoreElements: false,
                  scale: dpi //设置默认值 提高图片分辨率
              };
              html2canvas(document.querySelector("#capture"), options).then(canvas => {
                  // document.body.appendChild(canvas)
                  canvas.toBlob(function (blob) {
                      downloadBob(blob);
                  });
              });
          }
       function drawImage() {
              let dpi = window.devicePixelRatio || 2
              let options = {
                  useCORS: true,
                  ignoreElements: false,
                  scale: dpi //设置默认值 提高图片分辨率
              };
              html2canvas(document.querySelector("#capture"), options).then(canvas => {
                  let url = canvas.toDataURL('image/png') //base64
                  document.querySelector('#result').innerHTML = `海报`
              });
          }
    
          // 下载不了的 生成图片长按保存 
       function downloadBob(blob) {
              var a = document.createElement('a');
              var url = window.URL.createObjectURL(blob);
              var filename = '海报.png';
              a.href = url;
              a.download = filename;
              a.click();
              window.URL.revokeObjectURL(url);
          }
     
    

你可能感兴趣的:(html2canvas前端)