Generate images

Using html2Canvas to generate images is nothing new, but 1.0.0-rc.4 is recommended if you want to ensure that the plugin works properly on ios13. But this version does not provide a DPI field to improve the sharpness of the image, hopefully the later version will be optimized. But even without the DPI field, there are ways to handle it:

 const canvas = document.createElement('canvas');
 Canvas width is the width of the DOM node you want to draw * device pixel ratio
 canvas.width = width * window.devicePixelRatio;
 canvas.height = height * window.devicePixelRatio;
 canvas.style.width = `${width}px`;
 canvas.style.height = `${height}px`;
 const context = canvas.getContext('2d');
 // The brush scale is the device pixel ratio
 context.scale(window.devicePixelRatio, window.devicePixelRatio);
 html2canvas(dom, {canvas}).then((res) = > {
     console.log(res.toDataURL())
  })
Copy the code

Image cropping

Image cropping is handled at generation time

 <div className={styles.fu} ref={canvas}>
    <img className={styles.zi} src={WorksImg} alt="" />
 </div>
Copy the code

By controlling the width and height of the FU component and the display position of the image in the parent component, you can cut the image freely when generating a new image.

pictures

Spell more images into a new image, using CanvasRenderingContext2D. The drawImage () can draw the pictures to the canvas different coordinates (2 d) of the canvas (location), at the same time you can set the width of the image.