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

js and jquery to achieve tab status bar switching effect

Today we will make a simple case, using js and jq...

Detailed explanation of MySQL combined index method

For any DBMS, indexes are the most important fact...

About the configuration problem of MyBatis connecting to MySql8.0 version

When learning mybatis, I encountered an error, th...

Detailed explanation of selinux basic configuration tutorial in Linux

selinux ( Security-Enhanced Linux) is a Linux ker...

Introduction to the use of MySQL official performance testing tool mysqlslap

Table of contents Introduction Instructions Actua...

Introduction to scheduled tasks in Linux system

Table of contents 1. Customize plan tasks 2. Sync...

Detailed explanation of how to cleanly uninstall Docker

First, the server environment information: Reason...

Steps to install MySQL on Windows using a compressed archive file

Recently, I need to do a small verification exper...

Nginx tp3.2.3 404 problem solution

Recently I changed Apache to nginx. When I moved ...

Detailed explanation of the solution to image deformation under flex layout

Flex layout is a commonly used layout method nowa...

Specific use of stacking context in CSS

Preface Under the influence of some CSS interacti...

HTML Basics: The basic structure of HTML

The basic structure of HTML hypertext documents is...

How to configure the pdflatex environment in docker

Technical Background Latex is an indispensable to...

javascript input image upload and preview, FileReader preview image

FileReader is an important API for front-end file...

Tips on HTML formatting and long files for web design

<br />Related articles: 9 practical suggesti...