preface

I have heard that HTML2Canvas is relatively poor for a long time. However, due to the pressure of product demand, I have to realize the function of TURNING HTML into pictures. Since then, I have stepped on the road of filling the pit.

Html2canvas introduction

The detailed introduction of HTML2Canvas can be viewed here. In fact, in a simple way, THE DOM node generated by HTML can be drawn to the canvas through canvas, and then it can be converted into a picture according to your own requirements. So the official document also said that the final generated effect is not 100% the same, this point we should be prepared, no matter how, a little bit of small flaws are certain.

compatibility

Wechat browser

Using html2canvas

Use is also very simple, the official website write very clear stamp here

On the pit process

Why is wechat profile picture or other pictures missing in the generated pictures?

In fact, it involves cross-domain problem. Even the canvas of canvas has requirements for the image domain. How should we solve this problem?

  1. html2canvastheConfiguration itemsIn the configurationallowTaint:trueuseCORS:true(Both cannot be used together)
  2. Img tag addedcrossOrigin='anonymous'
  3. Image Server ConfigurationAccess-Control-Allow-OriginOr use a proxy

The third step is the most important. If you do not set it, the first two steps will not work.

The server needs to configure access-control-allow-origin information, such as PHP to add response header information, * wildcard indicates that any domain name is allowed:

header("Access-Control-Allow-Origin: *");
Copy the code

Or specify a domain name:

header("Access-Control-Allow-Origin: www.zhangxinxu.com");
Copy the code

But how can we cross domains on the front end if we don’t want to bother people on the back end? Html2canvas-proxy-nodejs or superagent. I’m using superagent. Here’s the example code:

const request = require('superagent'// Import const proxHost ='https://thirdwx.qlogo.cn'// Specify the cross-domain image address app.use('/proxy'.function (req, res, next) {
  let urlPath = req.url
  console.log('urlPath', urlPath)
  urlPath = decodeURI(urlPath)
  if(! urlPath) { console.log('urlPath is null')
    return next()
  }
  console.log('proxy-request: /proxy->' + `${proxHost}${urlPath}`)
  const reqStream = request.get(`${proxHost}${urlPath}`)
  reqStream.on('error'.function (err) {
    console.log('error', err)
  })
  console.log('------reqStream----')
  return reqStream.pipe(res)
})
Copy the code

So eventually I SRCHTTPS: the picture in the page / / thirdwx qlogo. To change for the proxy/cn/XXX XXX renderings are as follows:

2. What should I do if the image is blurred and has jagged edges?

Most of the results are found using the device pixel ratio, but in practice, there is still a jagged edge. This problem bothered me for a long time, and for a long time to find the relevant information, finally, the effort paid off, let me find a solution, in Github has provided a solution, you can click here, the source code to add two configuration items,scale and DPI, the scale parameter is recommended.

Source location: https://github.com/eKoopmans/html2canvas/tree/develop/dist

        let imgHeight = window.document.querySelector('.content').offsetheight // Gets the DOM heightlet imgWidth = window.document.querySelector('.content').offsetwidth // Gets the DOM widthletScale = window. DevicePixelRatio / / access device pixels than html2canvas (window. The document. QuerySelector ('.content'), {
            useCORS: true,
            scale: scale,
            width: imgWidth,
            height: imgHeight
        }).then((canvas) => {
          window.document.querySelector('.content').remove()
          let elemImg = `<img src='${canvas.toDataURL('image/png')} ' id='canvas-img' style='height: ${imgHeight}px; border-radius: 10px; width:${imgWidth}px'/>`
          window.document.querySelector('.container').innerHTML = elemImg
        })
Copy the code

The resulting image is the clearest and closest to the DOM

3. If the generated picture contains a TWO-DIMENSIONAL code, wechat long press the picture can not be recognized?

sundaypig
window.location.href

    location.href="www.abc.com/share/xxx"
Copy the code

PS: This problem can solve all the pages in the occasional two-dimensional code can not be recognized

4. Does the text in the generated picture have large spacing?

This is not a perfect solution for now. Try setting the spacing using the CSS property letter-spacing