html2canvas implements download or copy function

foreword

As the name suggests, html2canvas is to convert html elements into canvas canvas, and then export canvas to pictures. This article will present the functions shown in the title.

1. Property introduction

1. scrollX: type number , the default value is unclear. Solve the problem that the div element is too large to exceed the screen width, resulting in incomplete display of the generated canvas .
2. scrollY: type number , the default value is unclear. Solve the problem that the div element is too large to exceed the height of the screen, resulting in incomplete display of the generated canvas .
3. dpi: type number , the default value is not clear, the number of pixels. Determines the picture pixel size or clarity.
4. backgroundColor: type string , default #fff , to generate the background color of the canvas , if you want a transparent effect, directly assign the value to null . The transparent background may have black borders when opened in WeChat. The following code will talk about how to deal with the black border problem.
5. allowTaint: type boolean , default false, set whether to allow cross-domain. It should be noted that even if the front end is set to true , it cannot cross domains, and the header needs to be set on the back end to cross domains (the back end needs to include the Access-Control-Allow-Credentials attribute in the header of the response . At the same time, the Image on the front end must also be set crossOrigin attribute is Anonymous ). 6. height: type number , default null , the height of the generated canvas . Generally, this attribute is not used, because sometimes the canvas is relatively large and will exceed the display range, and this attribute will bring great limitations. 7. width: type number , default null , the width of the generated canvas . Generally, this attribute is not used, same as height . 8. letterRendering: type


boolean , false by default , useful when word spacing is set.
9. logging: type boolean , default false , output debugging information.
10. proxy: type string , default undefined , proxy address. It can solve cross-domain problems, but only one domain name can be solved. If there are multiple domain names cross-domain, it is not applicable.
11. taintTest: type boolean , default true , whether to check the image before rendering.
12. timeout: type number , default 0 , image loading delay time.
13. useCORS: type boolean , default false , to solve cross-domain problems, generally assigned as true (can be combined with Article 5).

Two, h5 tag elements

Tip: As can be seen from the code below, the contianer contains a lot of content. Next, convert these contents into canvas .
Note: If you use a lot of remote resources in your tags, try to avoid cross-domain issues as much as possible. Of course, it can also cooperate with the back end to solve this problem.

<div id="contianer">
   <img src="./top.png" />
   <div>
      <img src="./title.png" />
      <span>卧龙先生</span>
      <div>
          <img src="./qrcode.png" />
      </div>
   </div>
</div>

3. Generate canvas, download and copy pictures

Tip: When generating canvas and exporting pictures, there is a compression process, which will take some time, so open the debug panel and look at the log file.
1. Generate canvas . The following callbackBack function will be called in the 2nd and 3rd.

callBack() {
    
    
	const targetDom = document.getElementById('contianer');
    html2canvas(targetDom, {
    
    
    	useCORS: true,
        allowTaint: true,
        scrollX: 0,
        scrollY: 0,
        backgroundColor: null,
        dpi: window.devicePixelRatio * 2,
    }).then(canvas => {
    
    
    	// 注释1
        console.log('>>>> 生成canvas成功 >>>>');
    });
}

2. Download pictures. For example, we click the "Download Image" button to call the callBack function in Article 1 , and then type the following code at the position of Note 1 to download it locally.

const dom = document.createElement('a');
dom.href = canvas.toDataURL('image/png');
dom.download = '图片名称.png';
dom.click();

3. Copy pictures with one click. For example, if we click the "One-key Copy" button, the data can be written to the clipboard and then pasted into the target area. Still call the callback function of Article 1 , and then type the following code at the position of Note 1 to realize the copy and paste function.
(Note: ClipboardItem is a system function, how to call it correctly needs to be adjusted according to your own development language)

canvas.toBlob(blob => navigator.clipboard.write(
    [new window.ClipboardItem({
    
    [blob.type]: blob})]
))

4. Dealing with the black border problem

1. Common situations where black borders appear:
(1) The device configurations are different. For example, it is fine on Mac , but there are black bars on Windows ; it is fine on DingTalk, but there are black bars on WeChat; it is fine on Chrome browser , but there are black bars on Sogou browser Black border.
(2) Adaptation problem. Sometimes the width and height of the generated canvas will be a few more pixels, and these extra pixels may become black borders.
2. Solution:
No matter what the reason is, the black border is almost related to the transparency of the background, so let's come to a simple and easy-to-understand processing method. Without affecting the main content, we can set all the transparent parts to white. We can reset the data of the image attribute of the canvas before downloading or copying . The following code is still written in the comment 1 position.

let context = canvas.getContext('2d')
let image = context.getImageData(0, 0, canvas.width, canvas.height)
for(var i = 0; i < image.data.length; i += 4) {
    
    
	// 当该像素是透明的,则设置成白色   
	if(image.data[i + 3] == 0) {
    
    
		image.data[i] = 255
      	image.data[i + 1] = 255
   		image.data[i + 2] = 255
    	image.data[i + 3] = 255
   	}
}
context.putImageData(image, 0, 0);
// 之后,在此处继续写上第三部分的第2或第3条代码
Afterword

The technology is endless, and my understanding of html2canvas is only the tip of the iceberg. I hope it will be helpful to you.

Guess you like

Origin blog.csdn.net/HYNN12/article/details/115391854