Canvas-based QR code invitation letter generation plug-in and canvas invitation letter plug-in

Source: Internet
Author: User
Tags hasownproperty

Canvas-based QR code invitation letter generation plug-in and canvas invitation letter plug-in

Last year was the busiest year. I really didn't have time to write a blog. I watched another person in the Internet industry go down and urged everyone to put health first and put it seriously.
Well, let's get down to the point. This is the first blog post in 17 years. On this day, our product team ran to ask me: hi, lenny. You see there are various popular tools on the market that force H5, if you enter a name or enter a name, you can generate a real estate license for me. This can also be shared, and the transmission rate is high. Or you can click here to generate an invitation letter with one click, if you want to help me develop this function, I will play some promotional techniques.

 

The first reflection after I saw the effect was that I was sure that the canvas was spliced. Now the popular effect on the market is how to achieve it. I didn't go to the source code, but I had a clear idea. So I didn't get off work after dinner, I started my plug-in production journey.

First, we need to think about it. Since it is image processing, there must be image downloads. We know that the onload of images is asynchronous callback, all resources must be downloaded before the subsequent logic can be implemented. The logic of pre-resource download is critical. We not only need to process our subsequent processes after the onload event callback, at the same time, it must be executed only after all resources are loaded. Therefore, we need to construct a resource array roughly as follows:

[{       {            name: 'bg',            src: '../img/bg.jpg'        }, {            name: 'z',            src: '../img/z.png'        }]

To obtain the final complete event, we need to use a global variable to listen to onload or onerror times:

            var i = 1;            arr.forEach(function(obj, index, array) {                function onLoad() {                    _self[obj.name] = img;                    if (i < array.length) {                        ++i;                    } else {                        console.log('complete');                    };                }                var img = new Image();                img.onload = onLoad;                img.onerror = onLoad;                img.src = obj.src;

Okay. Now we get the resource loading completion event. We can continue with the following logic. Since it is based on canvas, of course, we need to create and initialize our canvas. Based on our own needs, this function only exists in the project I use no matter how many times it is initialized, so I made the following control:

init: function() {            var LCanvasImg_canvas = document.querySelector('#LCanvasImg_canvas');            if (LCanvasImg_canvas) {                LCanvasImg_canvas.width = this.params.cw;                LCanvasImg_canvas.height = this.params.ch;                LCanvasImg_canvas.style.display = this.params.display;                this.canvas = LCanvasImg_canvas;            } else {                var canvas = document.createElement('canvas');                canvas.id = 'LCanvasImg_canvas';                canvas.width = this.params.cw;                canvas.height = this.params.ch;                canvas.style.display = this.params.display;                document.body.appendChild(canvas);                this.canvas = canvas;            }            this.clear();        },

After the canvas is created, we need to implement the image rendering capability. canvas Image Rendering uses the drawImage method. According to the official documentation, this method has three parameter passing methods:

JavaScript Syntax 1 locates the image on the canvas: context. drawImage (img, x, y); JavaScript syntax 2 locates the image on the canvas and specifies the width and height of the image: context. drawImage (img, x, y, width, height); JavaScript syntax 3 cut the image and locate the cut part on the canvas: context. drawImage (img, sx, sy, swidth, sheight, x, y, width, height );

Therefore, we fully judge the drawImage parameter we call:

addImg: function(obj, callback) {            var _self = this;            var canvas = _self.canvas;            var ctx = canvas.getContext("2d");            if (obj.hasOwnProperty('sx') && obj.hasOwnProperty('sy') && obj.hasOwnProperty('sw') && obj.hasOwnProperty('sh') && obj.hasOwnProperty('x') && obj.hasOwnProperty('y') && obj.hasOwnProperty('width') && obj.hasOwnProperty('height')) {                ctx.drawImage(_self[obj.name], obj.sx, obj.sy, obj.sw, obj.sh, obj.x, obj.y, obj.width, obj.height);            } else if (obj.hasOwnProperty('x') && obj.hasOwnProperty('y') && obj.hasOwnProperty('width') && obj.hasOwnProperty('height')) {                ctx.drawImage(_self[obj.name], obj.x, obj.y, obj.width, obj.height);            } else if (obj.hasOwnProperty('x') && obj.hasOwnProperty('y')) {                ctx.drawImage(_self[obj.name], obj.x, obj.y);            } else {                ctx.drawImage(_self[obj.name], 0, 0);            }            _self.showImg();        },

Next, we need to develop the text generation capability. This is relatively simple. If you are familiar with canvas-related APIs, this part is not difficult:

AddFont: function (obj) {var _ self = this; var canvas = _ self. canvas; var ctx = canvas. getContext ("2d"); ctx. font = obj. fontsize + "px" + obj. fontfamily; // font size and font family var ftop = obj. ftop; // text top var fleft = obj. fleft; // text left ctx. textBaseline = "top"; // sets the text baseline when the text is drawn. Ctx.fillText(obj.txt, fleft, ftop); ctx. lineWidth = 1; ctx. fillStyle = "#000"; ctx. strokeStyle = "rgba (255,255,255, 0.4)"; ctx.strokeText(obj.txt, fleft, ftop );},

The last step is to generate a QR code, which is a bit pitfall and cannot be developed by myself. I chose an open-source plug-in: qrcode. Based on this plug-in, we can dynamically generate the base64 string of the QR code in an img. With this string, we can easily output the content to our canvas. To ensure the user experience, the outermost div of this plug-in is directly displayed: none to avoid interfering with our actual project.

<div id="qrcode" style="display: none;"></div>
/***** Initialize the QR code generation plug-in **/var qrdata = ''; var myqr = document. querySelector ('# myqr'); var qrcode = document. querySelector ('# qrcode'); var qr = new QRCode (qrcode, {width: 300, height: 300, colorDark: "#000000", colorLight: "# ffffff ", correctLevel: QRCode. correctLevel. L });

Since this img is dynamically changing, we must retrieve the base64 string in the callback of the img onload event, which is very important:

function buildQr () {    var img = qrcode.querySelector('img');    img.onload = function() {        qrdata = img.src;        main();    };    qr.makeCode(myqr.value);    }

OK. The preparation is complete. Next we need to initialize our plug-in. I have prefixed many configurable parameters:

Var canvasImg = null; function main () {// initialize canvasImg = new LCanvasImg ({cw: 768, // canvas width ch: 1163, // canvas height iw: '200', // output img width ih: 'auto', // output img height display: 'none' // canvas display}); // canvasImg for resource loading. load ([{name: 'qr ', src: qrdata}, {name: 'bg', src :'.. /img/bg.jpg '}, {name: 'Z', src :'.. /img/z.png '}], build );};

Have you seen the above build variable? We will write all the image generation logic in this build method. After loading the resource complete, the build will be executed;

Function build () {var farr = [{txt: document. querySelector ('# mytxt1 '). value, fontsize: 26, fontfamily: 'fzjt ', ftop: 140, fleft: 194}, {txt: 'hu xin', fontsize: 26, fontfamily: 'fzjt', ftop: 220, fleft: 394}, {txt: 'deng yixin', fontsize: 26, fontfamily: 'fzjt ', ftop: 220, fleft: 294}, {txt: document. querySelector ('# mytxt1 '). value, fontsize: 26, fontfamily: 'fzjt ', ftop: 220, fleft: 194}]; canvasImg. addImg ({name: 'bg ', x: 0, y: 0, width: 768, height: 1163}); farr. forEach (function (obj) {canvasImg. addFont (obj) ;}); canvasImg. addImg ({name: 'Z', x: 0, y: 0, width: 100, height: 100}); canvasImg. addImg ({name: 'Z', sx: 0, sy: 0, sw: 150, sh: 150, x: 100, y: 100, width: 100, height: 100}); canvasImg. addImg ({name: 'qr ', x: 400, y: 800, width: 200, height: 200}) ;}; window. onload = buildQr;

The last sentence is very important. Why do I need to use window here. onload event. If you are using webfont, after the webfont download is successful, there is still a short period of time to load the font into the browser, only in the window. the webfont font file takes effect only when the onload event occurs.
Final results:

 

The entire demo has been uploaded to github. If you need to do something similar, you can download this plug-in, which saves you a lot of time.
Address: https://github.com/xfhxbb/LCanvasImg

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.