This article mainly introduces the relevant information on the detailed explanation of html5 canvas WeChat poster sharing (personal climbing pit). The content is quite good. I will share it with you now and give it as a reference.
This article introduces canvas WeChat poster sharing, share it with everyone, the details are as follows:
Randomly generate a picture
Get the avatar and title of the WeChat user (get it by adjusting the back-end interface yourself)
Combine the user's avatar and title with a randomly generated picture to create a poster
Maybe the user on the previous page also filled in the wish text and also filled it in the picture
to achieve Rendering
Record the problems encountered in the process of implementing the function
canvas Long pressing in the WeChat browser is invalid and cannot be shared like img (then I will convert it to img)
After being converted to img, it can be displayed in the WeChat developer tools. Really The machine is invalid (I want to cry but no tears), Du Niang said it may be that the image is cross-domain ^-^
#The user avatar synthesis requires rounded corners, I said no, just look at the canvas api Documentation I have no love for Du Niang
If the text filled in the canvas exceeds the specified width, it must be wrapped. I said that I only know various text alignment methods that do not exceed the specified width ctx.textAlign = 'center' ;
The problem with canvas being blurry on a high-definition screen (it's so simple, I don't know why Du Niang is so verbose) is not canvas.witdt=innerWidth*devicePixelRatio
HTML Structure
<p class="imgBox" v-cloak> <img :src='imgSrc' v-if="imgSrc" / alt="Introduction to sharing of html5 canvas WeChat posters" > </p>
CSS
<style> *{ margin:0; padding:0; } body, html { width: 100%; height: 100%; } .imgBox { width: 100%; height: 100%; } img { width: 100%; display: block; } </style>
script
// js主要结构 new Vue({ el:'imgBox', data:{ urlParam: {},//获取url中的传值对象 randomNum: 1,//随机数用于确定那个祈福页 userName: '',//用户称呢 imgSrc: '',//合成最终图片 userImg: '',//用户头像图片 userMessage: '',//用户留言 }, methods: { // 分享到盆友圈 wxShareFriends: function () {}, // 初始化请求头 wxHttp: function () { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); }, // 获取随机数[1,10] randomNumbers() { this.randomNum = Math.ceil(Math.random() * 10) }, // 获取微信用户头像和称呢和用户输入祝福语 getUserInfo() { var vm = this; $.post('API请求地址', function (data) { if (data.code == 1) { vm.userImg = data.data.headimg; vm.userName = data.data.nickname; if (vm.randomNum % 2 == 0) { vm.userMessage= '红尘相遇,年华已老。岁月花开多少不在,古往今来相遇是一件既微妙。而又神圣的事情,红尘的情网中' } else { vm.userMessage = '红尘相遇,年华已老' } } vm.$nextTick(function () { vm.drawCanvasBgImg(); }) }) }, // 获取页面dpr和宽度 getWindowInfo() { var windowInfo = {}; windowInfo.dpr = window.devicePixelRatio; if (window.innerWidth) { windowInfo.width = window.innerWidth; } else { windowInfo.width = document.body.clientWidth; } return windowInfo; }, // 画活动页分享背景大图 drawCanvasBgImg () {}, // 在背景图片的画布上截取一个圆然后填充入用户头像 drawCanvasUserImg(canvas, ctx, dpr) {}, // 填写用户称呢或者用户留言 canvasFillText (canvas, ctx, dpr, circleR) {}, // 合成base64位分享图 convertCanvasToImage (canvas) { this.imgSrc = canvas.toDataURL("image/jpeg");//png有毒在安卓机下识别二维码无法跳转 this.$Spin.hide(); } } })
Drawing method steps
- ##drawCanvasBgImg ()
- drawCanvasUserImg (canvas, ctx, dpr)
- canvasFillText (canvas, ctx, dpr, circleR)
- convertCanvasToImage (canvas)
Draw activity page sharing background large image drawCanvasBgImg ()
//拿到数据后开始画背景大图 想法很简单就是把图片画到canvas中然后在画布上再画头像文字让后转成img drawCanvasBgImg () { var vm = this; var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); var clientWidth = this.getWindowInfo().width; //获取屏幕宽度用于canvas宽度自适应移动端屏幕 var dpr = this.getWindowInfo().dpr; ctx.globalCompositeOperation = "source-atop";//** 坑锯齿感觉没什么用不知道是不是用错地方了 ** canvas.width = dpr * clientWidth; //由于手机屏幕时retina屏,都会多倍渲染,用dpr来动态设置画布宽高,避免图片模糊 canvas.height = dpr * clientWidth * 609 / 375;//去掉微信头部的状态栏应该是603 没搞懂603还是不能让图片满屏直接多加到了609 var img = new Image(); img.crossOrigin = '';//死坑的图片跨域 (img.crossOrigin = "Anonymous"这种写法还是不能显示base64格式图片) img.src = "http://xxx" + this.randomNum + ".jpg"; img.onload = function () { ctx.drawImage(img, 0, 0, canvas.width, canvas.height); vm.drawCanvasUserImg(canvas, ctx, dpr); } },
User avatar drawCanvasUserImg (canvas, ctx, dpr)
// 在背景图片的画布上截取一个圆然后填充入用户头像 drawCanvasUserImg: function (canvas, ctx, dpr) { var vm = this; var circleR = 50 * dpr;//半径 var circleX = canvas.width / 2;//圆心X坐标 var circleY = 50 * dpr;//圆心Y坐标 var imgX = circleX - circleR;//图片X开始坐标 var imgY = circleY - circleR;//图片Y开始坐标 var imgWidth = 2 * circleR;//图片按圆形大小 var img = new Image(); img.crossOrigin = ''; img.src = this.userImg; img.onload = function () { ctx.save(); // 保存当前ctx的状态 ctx.arc(circleX, circleY, circleR, 0, 2 * Math.PI); //画出圆 ctx.clip(); //裁剪上面的圆形 ctx.drawImage(img, imgX, imgY, imgWidth, imgWidth); // 在刚刚裁剪的园上画图 ctx.restore(); // 还原状态 vm.canvasFillText(canvas, ctx, dpr, circleR); } },
Draw text in canvas
// 填写用户称呢或者用户留言 canvasFillText (canvas, ctx, dpr, circleR) { var fontSizeThis = dpr * 20 + 'px' + ' Arial'; var userNameY = 0;//用户名Y轴坐标 var userMessageX = dpr * 40;//用户留言X轴坐标 var userMessageY = 0;//用户留言Y轴坐标 var lastSubStrIndex = 0;//字符串下标 var lineWidth = 0;//一行宽度 var allTextWidth = 0;//所有字符宽度 ctx.font = fontSizeThis; // 需要用户名是写入用户名 if (this.userName) { userNameY = circleR * 2.5; ctx.fillStyle = "#0094ff"; ctx.textAlign = 'center'; ctx.fillText(this.userName, canvas.width / 2, userNameY); } if (this.userMessage) { userMessageY = userNameY + dpr * 35; ctx.fillStyle = "#000"; // 获取字符宽度 for (var i = 0; i < this.userMessage.length; i++) { allTextWidth += ctx.measureText(this.userMessage[i]).width; } // 字符串长度大于画布区域要换行 if (allTextWidth > canvas.width - 2* userMessageX) { for (var i = 0; i < this.userMessage.length; i++) { lineWidth += ctx.measureText(this.userMessage[i]).width; if (lineWidth > canvas.width - 2*userMessageX) { ctx.textAlign = 'left'; ctx.fillText(this.userMessage.substring(lastSubStrIndex, i), userMessageX, userMessageY); userMessageY += dpr * 25;//设置行高 lineWidth = 0; lastSubStrIndex = i; } if (i == this.userMessage.length - 1) { ctx.fillText(this.userMessage.substring(lastSubStrIndex, i + 1), userMessageX, userMessageY); } } } else { // 小于者居中显示 ctx.textAlign = 'center'; ctx.fillText(this.userMessage, canvas.width / 2, userMessageY); } } this.convertCanvasToImage(canvas); },The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website! Related recommendations:
canvas realizes the effect of dynamic ball overlapping code
canvas realizes the effect of love and rainbow rain
Method to achieve element picture mirror flip animation effect on canvas
The above is the detailed content of Introduction to sharing of html5 canvas WeChat posters. For more information, please follow other related articles on the PHP Chinese website!

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.


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

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

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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