Html5 canvas WeChat poster sharing (Personal pitfalls), html5canvas

Source: Internet
Author: User

Html5 canvas poster sharing (Personal pitfalls), html5canvas

This article introduces canvas posters and shares them with you as follows:

  1. Randomly generate an image
  2. Get the user's profile picture and name (call the back-end interface to obtain it)
  3. Combine the user's profile picture and name with a random image to form a poster.
  4. Maybe the previous page user still needs to fill in the desired text as well as the image.

Implementation

Record the problems encountered during function implementation

  1. Canvas cannot share long-pressed data in the browser as img (then I will convert it to img)
  2. After converting it to img, it can be displayed in the developer tool. The real machine is invalid (to cry), and Du Niang said it may be an image cross-domain ^-^
  3. The user's profile picture still needs rounded corners. I said no. I directly read the canvas api documentation and have no liking for du Niang.
  4. Text in the canvas exceeds the specified width. line feed is also required. I mean that only the alignment modes of the specified width are available, such as ctx. textAlign = 'center ';
  5. Canvas is blurred on the high-definition screen (it is super simple and I don't know how du Niang is so arrogant). It is not canvas. witdt = innerWidth * devicePixelRatio

HTML Structure

<div class="imgBox" v-cloak>    </div>

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 main structure new Vue ({el: 'imgbox', data: {urlParam :{}, // obtain the value passing object randomNum: 1 in the url, // The random number is used to determine the praying page userName: '', // What is the user name imgSrc:'', // synthesize the final image userImg: '', // The user avatar image userMessage: '', // user message}, methods: {// share to the basin friends circle wx?friends: function () {}, // initialize the request header wxHttp: function () {$. ajaxSetup ({headers: {'x-CSRF-TOKEN ': $ ('meta [name = "csrf-token"]'). attr ('content') }});}, // obtain the random number [] randomNumbers () {this. ra NdomNum = Math. ceil (Math. random () * 10)}, // get the user's profile picture and name, and enter the nickname getUserInfo () {var vm = this; $. post ('api request addresses', function (data) {if (data. code = 1) {vm. userImg = data. data. headimg; vm. userName = data. data. nickname; if (vm. randomNum % 2 = 0) {vm. userMessage = 'Red meet, old in years. It is a subtle thing to meet each other throughout the ages. And the holy thing, in the dust of the Internet '} else {vm. userMessage = 'Red dust meet, old ages '} vm. $ nextTick (function () {vm. drawCanvasBgImg () ;})}, // obtain the dpr and width of the page getjavaswinfo () {var javaswinfo ={}; windowInfo. dpr = window. devicePixelRatio; if (window. innerWidth) {javaswinfo. width = window. innerWidth;} else {javaswinfo. width = document. body. clientWidth;} return windowInfo;}, // draw an activity page to share the background image drawCanvasBgImg (){}, // capture a circle on the canvas of the background image and fill it with the user profile drawCanvasUserImg (canvas, ctx, dpr) {}, // enter the user name or message canvasFillText (canvas, ctx, dpr, circleR) {}, // synthesize base64-bit sharing map convertCanvasToImage (canvas) {this. imgSrc = canvas. toDataURL ("image/jpeg"); // png is toxic and cannot jump to this. $ Spin. hide ();}}})

Steps for drawing

  1. DrawCanvasBgImg ()
  2. DrawCanvasUserImg (canvas, ctx, dpr)
  3. CanvasFillText (canvas, ctx, dpr, circleR)
  4. ConvertCanvasToImage (canvas)

Draw activity pages to share the background chart drawCanvasBgImg ()

// After obtaining the data, start to draw a big image. The idea is very simple: Draw the image into the canvas, then draw the text on the canvas, and convert it to img drawCanvasBgImg () {var vm = this; var canvas = document. createElement ("canvas"); var ctx = canvas. getContext ("2d"); var clientWidth = this. getWindowInfo (). width; screen width // obtain the screen width. It is used for canvas width adaptive mobile terminal screen var dpr = this. getWindowInfo (). dpr; ctx. globalCompositeOperation = "source-atop"; // ** it feels useless when the groove is located. Do not know if the error code is correct. ** canvas. width = dpr * clientWidth; required bytes // because the retina screen on the mobile phone screen will be rendered multiple times, dpr is used to dynamically set the canvas width and height to avoid blurred canvas images. height = dpr * clientWidth * 609/375; // the status bar that is removed from the header should be 603. If you do not understand the status bar 603, do you still need to add the full screen Image to 609 var img = new Image (); img. crossOrigin = ''; // cross-origin (img. crossOrigin = "Anonymous" Cannot display base64 format images.) 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 profile picture drawCanvasUserImg (canvas, ctx, dpr)

// Capture a circle on the canvas of the background image and fill it with the user profile drawCanvasUserImg: function (canvas, ctx, dpr) {var vm = this; var circleR = 50 * dpr; // radius var circleX = canvas. width/2; // center X coordinate var circleY = 50 * dpr; // center Y coordinate var imgX = circleX-circleR; // Image X start coordinate var imgY = circleY-circleR; // Image Y start coordinate var imgWidth = 2 * circleR; // Image var img = new Image () according to the Circular size (); img. crossOrigin = ''; img. src = this. userImg; img. onload = function () {ctx. save (); // save the current ctx status ctx. arc (circleX, circleY, circleR, 0, 2 * Math. PI); // draw the circle ctx. clip (); // crop the circular ctx above. drawImage (img, imgX, imgY, imgWidth, imgWidth); // draw ctx on the newly cropped garden. restore (); // restore status vm. canvasFillText (canvas, ctx, dpr, circleR );}},

Draw text in canvas

// Enter the user name or message canvasFillText (canvas, ctx, dpr, circleR) {var fontSizeThis = dpr * 20 + 'px '+ 'arial'; var userNameY = 0; // User Name y axis coordinate var userMessageX = dpr * 40; // user message X axis coordinate var userMessageY = 0; // user message Y axis coordinate var lastSubStrIndex = 0; // string subscript var lineWidth = 0; // The width of a row var allTextWidth = 0; // The width of all characters 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"; // obtain the character width 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; // set the line height lineWidth = 0; lastSubStrIndex = I;} if (I = this. userMessage. length-1) {ctx. fillText (this. userMessage. substring (lastSubStrIndex, I + 1), userMessageX, userMessageY) ;}} else {// ctx is displayed in the center if it is less. textAlign = 'center'; ctx. fillText (this. userMessage, canvas. width/2, userMessageY) ;}} this. convertCanvasToImage (canvas );},

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.