Nowadays, there are many WeChat public account operation activities, all of which have the need to generate pictures. This article mainly introduces the relevant information about the solution for generating pictures on the mobile Html5 page. It has certain reference value. Friends in need can refer to it. , hope it helps you.
Nowadays, 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 circulated in Moments, which is conducive to product promotion!
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 in order to save time.
github address: html2canvas
Stop rambling, let’s look at things first! ! !
LiveDemo
/**
* 根据window.devicePixelRatio获取像素比
*/
function DPR() {
if (window.devicePixelRatio && window.devicePixelRatio > 1) {
return window.devicePixelRatio;
}
return 1;
}
/**
* 将传入值转为整数
*/
function parseValue(value) {
return parseInt(value, 10);
};
/**
* 绘制canvas
*/
async function drawCanvas (selector) {
// 获取想要转换的 DOM 节点
const dom = document.querySelector(selector);
const box = window.getComputedStyle(dom);
// DOM 节点计算后宽高
const width = parseValue(box.width);
const height = parseValue(box.height);
// 获取像素比
const scaleBy = DPR();
// 创建自定义 canvas 元素
var canvas = document.createElement('canvas');
// 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
canvas.width = width * scaleBy;
canvas.height = height * scaleBy;
// 设定 canvas css宽高为 DOM 节点宽高
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
// 获取画笔
const context = canvas.getContext('2d');
// 将所有绘制内容放大像素比倍
context.scale(scaleBy, scaleBy);
let x = width;
let y = height;
return await html2canvas(dom, {canvas}).then(function () {
convertCanvasToImage(canvas, x ,y)
})
}
/**
* 图片转base64格式
*/
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 today’s mobile phones have high-definition screens, if you don’t do any processing, blur will appear. Why does blur occur? This involves the device pixel ratio. devicePixelRatio js provides window.devicePixelRatio to obtain the device pixel ratio.
function DPR() {
if (window.devicePixelRatio && window.devicePixelRatio > 1) {
return window.devicePixelRatio;
}
return 1;
}This DPR function is to obtain the pixel ratio of the device. What should we do after obtaining the pixel ratio?
var canvas = document.createElement('canvas');
// 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
canvas.width = width * scaleBy;
canvas.height = height * scaleBy;
// 设定 canvas css宽高为 DOM 节点宽高
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
// 获取画笔
const context = canvas.getContext('2d');
// 将所有绘制内容放大像素比倍
context.scale(scaleBy, scaleBy);3. After obtaining 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 dom width and height. Think about it, why do you write this? Finally, when drawing, the drawn content is enlarged by the pixel ratio.
For example, the device width and height of iphone6S are 375 ) So are the design drafts designers usually give you 750*1334? So if you draw it one to one on a high-definition screen, it will be blurry. Look at the picture and speak 6S DPR=2

6plus DPR=3

4. Finally call canvas.toDataURL("image/png"); assign the value to image.src. Since images cannot be saved in WeChat, we can only generate image files and call WeChat's own long press to save. Go to the picture to album function, as shown in the picture:

Summary: The above is the entire content of this article, I hope it can be helpful to everyone's study. For more related tutorials, please visit Html5 Video Tutorial!
Related recommendations:
php public welfare training video tutorial
The above is the detailed content of Mobile Html5 page generation image solution. For more information, please follow other related articles on the PHP Chinese website!
Deconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AMHTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.
Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AMHTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.
H5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AMBest practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.
H5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AMWeb standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.
Is H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AMH5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.
H5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AMH5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.
What Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AMH5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo
H5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AMThe tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools






