Nowadays, the development related to wechat ecology is very common. In this issue, how to realize the dynamic generation of TWO-DIMENSIONAL code in the built-in browser of wechat and be able to identify by long press through qrcode.js and generate pictures through HTML2Canvas and long press to save

Just a couple of points

  • Wechat long press the pop-up recognition option principle
    • The wechat client detected a long pressimgThe label
    • Wechat takes the initiative to take screenshots and identify pictures, qr code recognition is used to take screenshots rather than throughimgThe label
    • Perform related operations after wechat recognition is successful
  • Base64
    • Base64 is one of the most common encodings for transmitting 8-bit bytecode on the network. Base64 is a method of representing binary data based on 64 printable characters
  • Blob
    • Blob objects in HTML5 are different from Blob objects in MySQL. In addition to storing binary data, Blob objects in HTML5 can also set the MINE type of the data, which is equivalent to the storage of files. Many other binary objects also inherit from this object
  • canvas.toDataURL([type, encoderOptions])
    • type: Specifies the image type. Default valueimage/png
    • encoderOptions: in order toimage/jpegimage/webpThe value ranges from 0 to 1. If the value exceeds the value, the default value 0.92 is used
    • Function: Convert images via Canvas

The preparatory work

  • Clear requirements in combination with wechat norms
    • Img tag in wechat can realize long press and pop up options through SRC attribute (save to mobile phone, qr code recognition will appear when the picture is QR code)
    • Two-dimensional code pictures for local pictures or server pictures (that is, do not need to be dynamically generated) only need to write normal code can be achieved
    • Wechat has its own set of adaptive logic and specifications for page images in the built-in browser. Canvas images and Base64 encoded images will have different problems on Android and ios phones
  • Determine the implementation scheme
    • This example uses third-party JS library to generate two-dimensional code
    • In view of the generated Base64 encoded image wechat cannot identify by long press, the format and image object need to be converted again in the front end
    • The generated picture is displayed in a pop-up window to avoid other elements affecting the recognition rate of wechat

The development environment

  • Development platform
    • MacOS
  • The development environment
    • Vue + node
  • Client environment
    • Google Chrome
    • Wechat Webview

The technical implementation

The technical implementation scheme of this example is implemented in the Vue project environment

Introduce third-party JS libraries

  • Provide two ways to introduce, two ways are different JS library, convenient for everyone to choose and use
    • Local introductionqrcode.js
    / / qrcode. Js making official document: https://github.com/davidshimjs/qrcodejs < script SRC = "static/js/qrcode. Js" > < / script >Copy the code
    • NPM intoqrcodejs2
    npm install qrcodejs2
    import qrCode from 'qrcodejs2'
    Copy the code

Component call

  • HTML

    <div class="qrcode-panel" id="qrcode"></div>
    Copy the code
  • JS

    • A simple call
    new QRCode(document.getElementById('qrcode'), 'your content'); // new QRCode(element, option) // element displays the element of the QRCode or the ID of the element // option parameter configurationCopy the code
    • The standard call
    var qrcode = new QRCode(document.getElementById("qrcode"), { text: "https://www.xxx.com?did=123456&id=123&userid=456", width: 160, // render: ColorDark: "#000000", // foreground colorLight: "# FFFFFF ", // Background color correctLevel: Qrcode.correctlevel. H // fault tolerance level}); // The fault tolerance level can be set as: Qrcode.correctlevel.l (maximum 7% errors can be corrected) qrcode.correctlevel.m (maximum 15% errors can be corrected) qrcode.correctlevel.q (maximum 25% errors can be corrected) Qrcode.correctlevel.h (maximum 30% errors can be corrected)Copy the code
    • Other public methods
    Qrcode.makecode (text) // set the content of the QRCode. Qrcode.clear () // clear the QRCodeCopy the code

Resetting the Image object

  • The reason for the reset is that the image and Canvas objects generated by the original JS cannot be recognized by long-pressing on the wechat terminal

    var canvas = document.getElementsByTagName('canvas')[0]; var img = this.convertCanvasToImage(canvas); document.getElementById("qrcode").append(img); ConvertCanvasToImage (canvas) {var Image = new Image(); SRC = Canvas. ToDataURL ("image/ PNG "); // Canvas. ToDataURL returns a string of Base64 encoded urls image.src = Canvas. image.id = 'qrcodeImg'; return image; }Copy the code

Follow-up details

  • At this point, a dynamic TWO-DIMENSIONAL code that can meet the recognition of long press has been generated. If you do not continue to process, there will be two two-dimensional codes.qrcode.jsThe generated QR code long press is not recognized, and after the reset object is able to achieve this function.
  • My processing method is to retain both two-dimensional codes, reposition the two-dimensional code picture, place the reset two-dimensional code picture on the upper layer that cannot recognize the two-dimensional code, and do not frequently operate the display and hiding of DOM nodes.
  • The generated QR code is passedappendIs inserted into the DOM node, which is required to shut down the operationcanvasimageGet rid of

Wechat’s built-in browser generates canvas pictures for saving

  • The above tutorial can realize dynamic generation of TWO-DIMENSIONAL code for saving and long press recognition, but if you need to generate HTML content to save canvas, there is a problem.
  • Several problems need to be paid attention to for saving:
    • Canvas is not cross-domain
    • Andrew wechat long press cannot save base64 image
    • Wechat limits the saving of Blob type pictures
    • usecanvas.toDataURLType used when drawingimage/jpegTo save

Technology selection

  • Use third-party JS librarieshtml2canvasFor processing
  • Principles of identification and generation:
    • A script takes a “screen shot” of a web page or part of a web page directly from the user’s browser
    • The “screen shot” is DOM based, so it may not be 100% accurate for the real representation, because it doesn’t make the actual screen shot, but builds the screen shot from the information available on the page
  • Existing problems:
    • It is because thehtml2canvasProcessing is not based on actual screenshots, so elements that are out of the flow or out of the flow cannot be intercepted
    • html2canvasOnly the content within the width and height range of the target element is intercepted
    • Property list with poor support for some CSS styles and poor compatibility
  • Some parameters that may be required
    • useCORS: Whether to attempt to load images from the server using CORS
    • async: Whether to parse and render elements asynchronously
    • scale: Scale used for rendering. The default is browser device pixel ratiowindow.devicePixelRatio
    • allowTaint: Whether the canvas is allowed to be polluted. The polluted canvas cannot be converted to base64 stream using toDataURL(). Please refer to some detailsReference here
    • More and morehtml2canvasClick here for the parameters

Introduce third-party JS libraries

  • usehtml2canvas
import html2canvas from 'html2canvas'
Copy the code

Component call

  • HTML
< div class = "html2canvas - conetent" ref = "canvasContent" > < img SRC = "/ static/images/canvas. JPG" > < span > test Title < / span > < / div > < button@click ="showCanvas()"> </button>Copy the code
  • JS
    • usehtml2canvasThe recommended PROMISE method
showCanvas() { let self = this; html2canvas(self.$refs.canvasContent).then(function(canvas) { self.imgUrl = canvas.toDataURL(); self.showCanvasImg = true; }); } // Asynchronously parse the call and render element showCanvas() {let self = this; html2canvas(self.$refs.canvasContent { async: true }).then(canvas => { self.imgUrl = canvas.toDataURL(); self.showCanvasImg = true; }); }Copy the code

Implementation effect

The source address

  • Complimentary Github source address

Past oliver

Long [word] baidu and good interview after containing the answer | the nuggets technology essay in the future

Front end practical regular expression & tips, all throw you 🏆 nuggets all technical essay | double festival special articles

Vue3.0 Responsive data principle: ES6 Proxy

Read on to make your interviewer fall in love with you

Remember a painful experience

Front-end performance optimization -HTML, CSS, JS parts

Front-end performance optimization – Page loading speed optimization

Front-end performance optimization – Network transport layer optimization