Home Web Front-end JS Tutorial js and canvas synthesize pictures to create WeChat public account posters

js and canvas synthesize pictures to create WeChat public account posters

Mar 16, 2018 am 09:31 AM
canvas javascript

This time I will bring you the function of synthesizing js and canvas pictures to make WeChat public account posters, and the function of synthesizing js and canvas pictures to make WeChat public account posters Precautions Yes Which ones, the following are practical cases, let’s take a look.

In the development of WeChat public accounts, there is often a need to add a picture, avatar, nickname or other data to generate your own QR code poster or generate a sharing poster

This Requirements, PHP's gd library can be implemented, but using the server for image synthesis will consume a lot of server resources

So we can consider using the following methods to achieve

1: js canvas image Synthesis method

 $(function () {
        draw(function () {//生成之后的回调
            $('#img')[0].innerHTML='<img  src="/static/imghw/default1.png" data-src="'+base64[0]+'" class="lazy" alt="js and canvas synthesize pictures to create WeChat public account posters" >';//将base生成图片
        });
    });
    var data=[图片1地址,图片2地址,图片3地址];
    base64=[];//用于保存生成之后的base64
    function draw(fn) {
        var img1= new Image;
        img1.src = data[0];
        img1.onload = function () {//这步必须,因为图片加载是异步的,必须等图片加载完成才开始下面的这些步骤
            var c = document.createElement('canvas'),
                    ctx = c.getContext('2d');
                        c.width = img1.naturalWidth;
                        c.height = img1.naturalHeight;
                        ctx.rect(0, 0, c.width, c.height);
                        ctx.fillStyle = '#fff';
                        ctx.fill();
            //生成一张图片1的底图
                         
            /*下面是为底图增加上文字*/
            ctx.drawImage(img1, 0, 0, c.width, c.height);(绘制图片资源,x坐标,y坐标,宽,高)
            //设置字体样式
            ctx.font = "24px Courier New";
            //设置字体填充颜色
            ctx.fillStyle = "write";
            //从坐标点(92,800)开始绘制文字
            ctx.fillText("这是文字内容", 92, 800);
            /*上面是增加文字,可以无限加*/
             
             
            var img2= new Image;
            img2.src = data[1];
            img2.onload = function () {//同理,如果是加载图片的话,需要等图片加载出来再下一步,所以要加onload
                ctx.drawImage(img2, 245, 660, 150, 150);(绘制图片资源,x坐标,y坐标,宽,高)
                    base64.push(c.toDataURL("image/jpeg", 1));//如果绘制完成了,就把base64数据填进数组,然后回调,没完成则继续这步
                fn();//回调
            };
        };
    }
 ///如果是坐标相同,或者觉得代码这样不美观的,可以使用递归方法实现onload的步骤,例如:
 
    function draw(fn) {
             
         a(0);
          
         fn();
    }
  
 function a(i){ 
       if (i == 0) {
         var img1= new Image;
        img1.src = data[0];
        img1.onload = function () {
            var c = document.createElement('canvas'),
            ctx = c.getContext('2d');
                        c.width = img1.naturalWidth;
                        c.height = img1.naturalHeight;
                        ctx.rect(0, 0, c.width, c.height);
                        ctx.fillStyle = '#fff';
                        ctx.fill();
            //生成一张图片1的底图
                         
            /*下面是为底图增加上文字*/
            ctx.drawImage(img1, 0, 0, c.width, c.height);(绘制图片资源,x坐标,y坐标,宽,高)
            //设置字体样式
            ctx.font = "24px Courier New";
            //设置字体填充颜色
            ctx.fillStyle = "write";
            //从坐标点(92,800)开始绘制文字
            ctx.fillText("这是文字内容", 92, 800);
            /*上面是增加文字,可以无限加*/
            a(1);//到第2个步骤
        }
        } else if (i == 1) {
           var img2= new Image;
            img2.src = data[1];
            img2.onload = function () {//同理,如果是加载图片的话,需要等图片加载出来再下一步,所以要加onload
                ctx.drawImage(img2, 245, 660, 150, 150);(绘制图片资源,x坐标,y坐标,宽,高)
                    base64.push(c.toDataURL("image/jpeg", 1));//如果绘制完成了,就把base64数据填进数组,然后回调,没完成则a(2)到第三步;
                return;
            };
        } 
   }
Copy after login

2: Use html2canvas to save web pages into images //Need to introduce html2canvas.js

<div>
    <img  class="qrbg lazy" src="/static/imghw/default1.png" data-src="图片1" alt="js and canvas synthesize pictures to create WeChat public account posters" >
    <img  class="qrcode lazy" src="/static/imghw/default1.png" data-src="图片2" alt="js and canvas synthesize pictures to create WeChat public account posters" >
    <span><img  class="touxiang lazy" src="/static/imghw/default1.png" data-src="图片3" alt="js and canvas synthesize pictures to create WeChat public account posters" >文字</span>
    <div></div>
</div>
//使用css进行网页布局
Copy after login
$(window).load(function(){
    var shareContent = $(".qrbg")[0]; 
    var width = shareContent.offsetWidth; 
    var height = shareContent.offsetHeight;
    $(".qrcodepic").height(height);
    var canvas = document.createElement("canvas"); 
    var scale = 2; 
    canvas.width = width * scale; 
    canvas.height = height * scale; 
    canvas.getContext("2d").scale(scale, scale); 
    var rect = shareContent.getBoundingClientRect();
    canvas.getContext("2d").translate(-rect.left,-rect.top);
    var opts = {
        scale: scale, 
        canvas: canvas, 
        width: width, 
        height: height,
        useCORS:true
    };
    html2canvas($(".qrcodepic"), opts).then(function (canvas) {
        dataURL =canvas.toDataURL("image/png");
        $(".qrcodemain").html("<img  src="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/857/211/485/1521163699667209.png" class="lazy" alt="js and canvas synthesize pictures to create WeChat public account posters" >");
    });
});
Copy after login

js and canvas synthesize pictures to create WeChat public account posters

js and canvas synthesize pictures to create WeChat public account posters

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

How to use JQ to right-click to collect web pages

The API that jQuery must master

How to implement file upload with progress bar animation

jQuery implements form verification after multi-layer verification

The above is the detailed content of js and canvas synthesize pictures to create WeChat public account posters. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Learn the canvas framework and explain the commonly used canvas framework in detail Learn the canvas framework and explain the commonly used canvas framework in detail Jan 17, 2024 am 11:03 AM

Explore the Canvas framework: To understand what are the commonly used Canvas frameworks, specific code examples are required. Introduction: Canvas is a drawing API provided in HTML5, through which we can achieve rich graphics and animation effects. In order to improve the efficiency and convenience of drawing, many developers have developed different Canvas frameworks. This article will introduce some commonly used Canvas frameworks and provide specific code examples to help readers gain a deeper understanding of how to use these frameworks. 1. EaselJS framework Ea

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Explore the powerful role and application of canvas in game development Explore the powerful role and application of canvas in game development Jan 17, 2024 am 11:00 AM

Understand the power and application of canvas in game development Overview: With the rapid development of Internet technology, web games are becoming more and more popular among players. As an important part of web game development, canvas technology has gradually emerged in game development, showing its powerful power and application. This article will introduce the potential of canvas in game development and demonstrate its application through specific code examples. 1. Introduction to canvas technology Canvas is a new element in HTML5, which allows us to use

Where to write canvas code Where to write canvas code Dec 20, 2023 pm 03:17 PM

Canvas code can be written inside the <body> tag of an HTML file, usually as part of the HTML document. The core of the Canvas code is to obtain and operate the context of the Canvas element. The reference to the Canvas element is obtained through document.getElementById('myCanvas') , and then use getContext('2d') to get the 2D drawing context.

See all articles