La la la, let’s talk about the requirements first. The product wants users to share a picture to WeChat, QQ and other platforms within our app. The image contains the user's name, avatar, and a QR code with their own information. Then, how to generate this poster~~~
First of all, our boss told me that there is a plug-in called html2canvas. Its function is to convert DOM nodes into pictures, which is a good thing. I tested it, and it does work, but ~ this plug-in is a bit big. It feels like a loss to introduce such a big thing to meet the needs of posters! ! ! So, I’d better draw one myself~
First, the renderings
Dangdangdangdang~~~The final generated poster includes an avatar, name and QR code. Of course, the QR code on the picture is Baidu’s QR code~ Finally, base64 is generated for sharing on major platforms.
Without further ado, here’s the code (I haven’t compiled this code because I’m lazy...)
<canvas id=myCanvas width=750 height=1200 style=border:1px solid #d3d3d3;background:#ffffff;></canvas>
The DOM node is very simple, just generate a canvas tag and write some attributes as you like~
var canvas = document.getElementById(myCanvas); //Get canvas node function imageToCanvas(canvas,url1,url2,code) { //Pass in canvas node background image url1 avatar url2 QR code code var ctx = canvas.getContext(2d ); var img1 = new Image(); img1.src = url1; //I won’t explain the previous one, generate an image img1.onload = function(){ ctx.drawImage(img1,0,0); //When the image is loaded, it is assigned to the canvas starting from 0 0. var img2 = new Image(); img2.src = url2; img2.onload = function(){ ctx.save(); //Save the current canvas state ctx.arc(374, 134, 44, 0, 2 * Math. PI); //The cutting operation cuts the square avatar into a circle//Cut out the circle from the canvas ctx.clip(); //Crop ctx.drawImage(img2, 330, 90, 88, 88); //Put img2 at 330 90 coordinates with size 88 ctx.restore(); //Release the canvas state ctx.font=28px Arial; ctx .textAlign=center; ctx.fillStyle ='#FFFFFF'; //The previous step is to set the text attribute to center ctx.fillText(your name is Shenma, 375,220); //The text here is hard-coded. In practice, passing more parameters is ok var img3 = new Image(); img3.src = code; img3.onload = function() { ctx.drawImage(img3,136,554,478,478); //Similarly add image var imgCode = convertCanvasToImage(canvas); //Convert the image to base64 console.log(imgCode.getAttribute('src')) } } }}imageToCanvas(canvas,1.png,'3.jpeg','code.png') ; //Initialization function convertCanvasToImage(canvas) { var image = new Image(); image.src = canvas.toDataURL(image/png); //Convert canvas to img return image;}
In this way, you can get a base64 and then use it.
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.