JavaScript mobile H5 image generation solution explanation

JavaScript mobile H5 image generation solution explanation

Now there are many WeChat public account operation activities, and there is a need to generate pictures. After the pictures are generated, they can be sent to friends and spread to the circle of friends, which is conducive to the promotion of products!

1.

You can use canvas to generate images, but since there is already an open source library called html2canvas, I didn't write it myself to save time.

github address: html2canvas

LiveDemo

    /**
     * Get the pixel ratio according to window.devicePixelRatio*/
    function DPR() {
        if (window.devicePixelRatio && window.devicePixelRatio > 1) {
            return window.devicePixelRatio;
        }
        return 1;
    }
    /**
     * Convert the passed value to an integer */
    function parseValue(value) {
        return parseInt(value, 10);
    };
    /**
     * Draw canvas
     */
    async function drawCanvas (selector) {
        // Get the DOM node you want to convert const dom = document.querySelector(selector);
        const box = window.getComputedStyle(dom);
        // DOM node calculated width and height const width = parseValue(box.width);
        const height = parseValue(box.height);
        // Get pixel ratio const scaleBy = DPR();
        // Create a custom canvas element var canvas = document.createElement('canvas');
        // Set the canvas element attributes width and height to DOM node width and height * pixel ratio canvas.width = width * scaleBy;
        canvas.height = height * scaleBy;
        // Set canvas css width and height to DOM node width and height canvas.style.width = `${width}px`;
        canvas.style.height = `${height}px`;
 
        // Get the brush const context = canvas.getContext('2d');
 
        // Scale all drawn content by pixel ratio context.scale(scaleBy, scaleBy);
 
        let x = width;
        let y = height;
        return await html2canvas(dom, {canvas}).then(function () {
            convertCanvasToImage(canvas, x, y)
        })
    }
 
    /**
     * Convert the image to base64 format*/
    function convertCanvasToImage(canvas, x, y) {
        let image = new Image();
        let _container = document.getElementsByClassName('container')[0];
        let _body = document.getElementsByTagName('body')[0];
        image.width = x;
        image.height = y;
        image.src = canvas.toDataURL("image/png");
        _body.removeChild(_container);
        document.body.appendChild(image);
        return image;
    }
    drawCanvas('.container')

2.

Since current mobile phones all have high-definition screens, the images will appear blurry if you don’t process them. Why will they appear blurry? This involves the device pixel ratio devicePixelRatio js provides window.devicePixelRatio to get the device pixel ratio

function DPR() {
        if (window.devicePixelRatio && window.devicePixelRatio > 1) {
            return window.devicePixelRatio;
        }
        return 1;
    }

This DPR function is used to obtain the pixel ratio of the device. What should be done after obtaining the pixel ratio?

var canvas = document.createElement('canvas');
        // Set the canvas element attributes width and height to DOM node width and height * pixel ratio canvas.width = width * scaleBy;
        canvas.height = height * scaleBy;
        // Set canvas css width and height to DOM node width and height canvas.style.width = `${width}px`;
        canvas.style.height = `${height}px`;
 
        // Get the brush const context = canvas.getContext('2d');
 
        // Scale all drawn content by pixel ratio context.scale(scaleBy, scaleBy);

3.

After getting the device pixel ratio, multiply canavs.width and canvas.height by the device pixel ratio, which is scaleBy; at this time, set canvas.style.width and canvas.style.height to the width and height of the dom. Think about why you write it this way? Finally, when drawing, enlarge the pixel ratio of the drawn content by times

For example, the device width and height of iPhone 6S is 375 X 667, and the window.devicePixelRatio of 6S = physical pixels / dips (2=750/375). So are the designs that designers usually give you 750*1334?

So if you draw it on a high-definition screen at a 1:1 ratio, it will be blurry. See the picture for yourself. 6S DPR=2

6plus DPR=3

4.

Finally, call canvas.toDataURL("image/png"); assign it to image.src. Since WeChat cannot save pictures, we can only generate picture files and call WeChat's built-in long press function to save pictures to the album.

This is the end of this article about the solution of generating images with JavaScript on mobile H5. For more relevant content about generating images with JavaScript on mobile H5, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Native js generates image verification code
  • js generates image thumbnails through canvas
  • Java uses Phantomjs to realize the function of generating pictures
  • Node.JS uses pure JavaScript to generate image or slider verification code function
  • An example of how to dynamically generate image verification codes in JSP pages
  • js saves the image generated by canvas, or directly saves an image
  • Detailed explanation of the technology of generating image verification code in JSP development
  • Use captchapng module to generate image verification code in Nodejs
  • Generate web page snapshots in image format based on linnux+phantomjs

<<:  Detailed steps to configure my.ini for mysql5.7 and above

>>:  How to get the current time using time(NULL) function and localtime() in Linux

Recommend

React Router V6 Updates

Table of contents ReactRouterV6 Changes 1. <Sw...

Chinese and English font name comparison table (including Founder and Arphic)

In CSS files, we often see some font names become...

MySQL Quick Data Comparison Techniques

In MySQL operation and maintenance, a R&D col...

MySQL 8.0.12 installation configuration method and password change

This article records the installation and configu...

Docker Machine in-depth explanation

Differences between Docker and Docker Machine Doc...

Tutorial on installing rabbitmq using yum on centos8

Enter the /etc/yum.repos.d/ folder Create rabbitm...

An audio-visual Linux distribution that appeals to audiophiles

I recently stumbled upon the Audiovisual Linux Pr...

Detailed example of creating and deleting tables in MySQL

The table creation command requires: The name of...

How to let https website send referrer https and http jump referrer

This article describes a proposal for a metadata ...

Vue custom v-has instruction to implement button permission judgment

Application Scenario Taking the background manage...

How to connect Navicat to the docker database on the server

Start the mysql container in docekr Use command: ...

Detailed explanation of HTML form elements (Part 1)

HTML forms are used to collect different types of...

How to start tomcat using jsvc (run as a normal user)

Introduction to jsvc In production, Tomcat should...