Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use HTML to realize screenshot function

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use HTML to achieve screenshot function, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Preface

Recently, project requirements always have the function of generating pictures on the HTML page, so I want to record the problems I have encountered in the process and deepen my impression, and you can review them later if you forget. Our project uses the html2canvas plug-in, and there are other plug-ins, such as dom-to-image and rasterizehtml, which can be used on demand.

Summary of html2canvas usage questions

What is introduced in the project is the 0.5.0-beta4 version of the cdn link, which calls the method html2canvas (dom,options) directly. The first parameter is the dom object you want to draw, and the second parameter is some drawn configuration parameters. I have tried some parameters and have not figured out what the specific function is. I can read the html2canvas document by myself, and add the code directly to the code I use:

/ / generate function generateImg () {var shareContent = the (native) dom object of the part of the document.body;// that needs to be drawn. Note that the container width does not use a percentage, use a fixed width, and avoid the scaling problem var width = shareContent.offsetWidth; / / get (native) dom width var height = shareContent.offsetHeight; var offsetTop = shareContent.offsetTop / / offset from the top of the element / / var rect = shareContent.getBoundingClientRect (); var canvas = document.createElement ('canvas'); / / create canvas object var context = canvas.getContext (' 2d'); var scaleBy = 3; / / Pixel density (you can also use custom scaling) canvas.width = width * scaleBy / / here, because the dom drawn is fixed width and centered, there is no offset canvas.height = (height + offsetTop) * scaleBy; / / pay attention to the height problem. Because there is a distance at the top, it is necessary to add the top distance to solve the image height offset problem canvas.height = height * scaleBy; / / context.translate (0,-offsetTop). / / canvas offset context.scale (scaleBy, scaleBy) Html2canvas (shareContent, {logging: true, / / whether to print the log or not Default false taintTest: true, / / check that each picture has been loaded and completed. / / the added scale parameter canvas: canvas, / / custom canvas width: width, / / dom original width height: height, / / dom original height useCORS: true / / allow cross-domain onrendered: function (canvas) {/ / callback var url = canvas.toDataURL ("image/png") after the page is drawn successfully / / the operation after generating the picture}});} picture blurring resolution

Due to the problem of pixel ratio (DPR = device pixels / CSS pixels), the screenshot looks good on the computer, but it will be very blurred on the phone. When drawing a picture, you can enlarge the picture according to the pixel ratio, define the width of the picture when you use it, or customize the zoom ratio. The zoom ratio is not as large as possible, and it may cause problems if it is too large. The code to calculate the pixel ratio:

Function getPixelRatio (context) {var backingStore = context.backingStorePixelRatio | | context.webkitBackingStorePixelRatio | | context.mozBackingStorePixelRatio | | context.msBackingStorePixelRatio | | context.oBackingStorePixelRatio | | context.backingStorePixelRatio | | 1; return (window.devicePixelRatio | | 1) / backingStore;}

Try not to use background pictures when drawing. Use img directly to make it clearer.

Cross-domain problem of picture

Once the page used the Wechat avatar, set useCORS: true can not display the avatar, set allowTaint:true to report a direct error can not use toDataURL may not be able to export the contaminated canvas; finally, we have to find Baidu

Modify the Nginx configuration file, because it is also used in other parts of our project, so it is not convenient to modify, you can modify the reference:

Location ^ ~ / wechat_image/ {add_header 'Access-Control-Allow-Origin' "$http_origin" always; add_header' Access-Control-Allow-Credentials' 'true' always; add_header' Access-Control-Allow-Methods' 'GET, OPTIONS' always; add_header' Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always Proxy_pass http://thirdwx.qlogo.cn/;}

Convert the image to base64 format and set CrossOrigin= "anonymous". After trying, the image cannot be generated normally even if there is a cache. You need to concatenate a random parameter to solve the cache problem. Android is fine, but not on ios.

Later, it was found that CrossOrigin= "anonymous" was directly set on the img tag of Wechat avatar, that is,

The request for Wechat avatar can be found on access-control-allow-origin: *, Android and ios. If you have tried other methods before, you may need to clear the cache, otherwise Android will mislead you that it cannot be displayed properly.

Recently, it was found that proxy is configured as a cross-domain url in the options of html2canvas.

A problem flashes when generating a picture replacement page

The previous generation of pictures, did not appear this problem, the most recent replacement when the page flash, thinking that the picture is not too big, I will save the two active pictures comparison is not, specific I still do not understand, but first write an empty img tag in dom and then replace the generated src to img, to determine the completion of the picture loading and then hide the drawn dom to solve this problem.

The css style disappears beyond the display ellipsis

Html2canvas does not support the generation of ellipses in css style. Baidu has found a solution and replaced it with ellipses when judging by js that it exceeds the height of the parent box.

$(".info _ text_box") .each (function () {var divH = $(this) .height (); var $p = $("p", $(this)) .eq (0) While ($p.outerHeight () > divH) {$p.html ($p.html (). Replace (/ (\ s) * ([a-zA-Z0-9] + |\ W) (\.)? $/, "));};}); generate a picture before the font is displayed when the web font is introduced

_ window.onload=function () {} is executed after the page resource is loaded, but it is not supported in ios. Later, it was found that when the font size was larger than 300px, the width of different fonts varied greatly, so the timer was used to judge whether the font was loaded successfully. However, because the font file was loaded too slowly, the use of special fonts was abandoned.

/ / complete function fn_fontWatch (fontFamily, cb) {function fn_gen_span_with_font (font) {var span=document.createElement ('span'); span.style.cssText = "display:block;position:absolute;top:-9999px;left:-9999px;font-size:300px;width:auto;height:auto;line-height:normal;margin:0;padding:0;font-variant:normal" by judging the font content width White-space:nowrap;font-family: "+ font; span [XSS _ clean] = 'BESbswy'; document.body.append (span); return span;}; var span_default = fn_gen_span_with_font (' serif'); var span_default_width = span_default.offsetWidth; document.body.removeChild (span_default) Var span_font = fn_gen_span_with_font (fontFamily +', serif'); var fn_check_loop = function () {if (span_default_width! = = span_font.offsetWidth) {document.body.removeChild (span_font); cb () } else {window.setTimeout (fn_check_loop,500);}}; fn_check_loop ();}; other questions

An activity needs to determine the order of entering the page. Html2canvas draws the picture by traversing the dom. When the picture is generated, it will be executed again except js, which leads to similar refresh of the page record order. The final order is solved by ajax request.

Html2canvas will only intercept the visible content in the page, and the elements of display: none and visibility:hidden cannot be intercepted.

There are some changes in the text when the picture is generated. For example, the number 1 in Android has changed obviously, and the position of the text has moved down a little. The reason I did not find is that it does not have much impact. At present, I have not solved it.

Thank you for reading this article carefully. I hope the article "how to use HTML to achieve screenshot function" shared by the editor will be helpful to everyone. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report