Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use canvas to share screenshots

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to use canvas to share screenshots, the article is very detailed, has a certain reference value, interested friends must read it!

Realization: first, body part

I use react for the framework. Painting sharing is realized by native canvas and js. So don't worry about vue, Mini Program, native H5 can also adapt.

First, build canvas

Some inline code chips are shown below.

/ / ref is the way for react to get the canvas element. You can also use id, and then use the getElementById () method to obtain the width and height of canvas//, which needs to be converted into two-quadruple images to improve clarity, otherwise it will lead to blurred screenshots of sharing, lack of clarity / / clicking the sharing button to trigger the this.shareComponent (this.getUrlImg) method / / non-react framework, ignoring the rest of the code. Directly trigger the sharing function {this.setState ({shareModal:true}, () = > {this.shareComponent (this.getUrlImg)})}} > share activity implementation: 2. JS:

ShareComponent function:

The / / function accepts a callback function, which is used to convert canvas to png image format after the painting is finished. / / the mobile canvas cannot be saved by long-term press. It must be passed to img before it can be saved. ShareComponent = (callback) = > {let suncode = this.state.suncode / / WeChat Mini Programs Sun Code let activityName = this.state.activityName / / activity title let backgroundImg = this.state.backgroundImg / / background map let postShareDesc= this.state.postShareDesc / / share description field let img = new Image () img.crossOrigin= "anonymous"; / / key, deal with the cross-domain problem of pictures! Let _ t = this / / limit activity title, up to 10 words, more than. Omit if (activityName.length > 10) {activityName=activityName.slice (0J10) + '...'} / / since canvas text cannot be wrapped automatically, we need to do a word wrap and a word limit to prevent it from exceeding the canvas range let arrDescribe = [] let maxLeng = postShareDesc.length/20 / / sharing description with 20 words per line. Up to 8 lines if (maxLeng= > 8) {maxLeng= 8 / / maximum 8 lines} / / postShareDesc is the share description field for (let I = 0) I {ctx.fillText (item,80700+index*100);}) / / sharing title ctx.font= "64px Arial"; ctx.fillStyle='#000'; ctx.fillText (activityName,520,1320); / / sharing prompt ctx.font= "48px Arial"; ctx.fillStyle='#999'; ctx.fillText ('long press Mini Program code for details', 520Jol 1420) / / sharing hint ctx.font= "48px Arial"; ctx.fillStyle='#999'; ctx.fillText ('shared from [XXXX]', 520,1500); / / Segmentation ctx.moveTo (1120Power1160); ctx.lineTo (80meme1180); ctx.strokeStyle= "# E8E8E8" ctx.stroke () / / img1 is Mini Program Sun Code let img1 = new Image () img1.crossOrigin= "anonymous"; / / the key is to deal with the cross-domain problem when converting Sun Code into base64 format images img1.onload = function () {ctx.drawImage (img1, 80, 1200340340) callback (canvas)} Sun Code is assigned to img1 img1.src = suncode / / frame ctx.strokeStyle= "# f5f5f5" Ctx.rect; ctx.stroke ();} / / timeStamp event property returns a timestamp. Indicates the date and time when the event occurred (milliseconds since epoch). / / usage of URL timestamp: function: to prevent browser caching. / / adding a random number or timestamp after URL is usually used to prevent browsers (clients) from caching pages. The browser cache is cached based on URL. / / if the page allows caching, access the same URL again before the cache expires, and the browser will not send the request to the server again, but get the specified resource directly from the cache. / / when a random number or timestamp is appended to the end of the URL, it is guaranteed that each time a new request is actually generated and that the Web server does not attempt to cache the response from the server. Const a = `${backgroundImg}? timeStamp=` + (new Date ()); img.src = a} / / after the painting is completed, it must be converted to img, otherwise the mobile device will not be able to press save / / until the painting is completed before callback. If you use canvas.toDataURL ('image/png') conversion directly, it will result in sharing images with only dead text, no requested pictures and text. Asynchronous problem getUrlImg= (canvas) = > {let dataImg = new Image () try {dataImg.src = canvas.toDataURL ('image/png')} catch (e) {console.log (e) } let urlImg = dataImg.src / / urlImg is the img path this.setState ({urlImg}, () = > {})}: 3. When canvas replaces imgs://, the canvas must be hidden and then replaced with imgs, so that the mobile end can press Save / / css .canvasImg to add display:none to hide canvas / / then use the img converted by canvas, and set the width and height of img to 25% canvas / because in order to improve clarity I use quadruple image recompression to improve clarity, so img needs to shrink 25% / / display:none / / crossOrigin= "Anonymous" to deal with cross-domain problems.

/ / width:25% . Height:25% div className= {styles.shareTips} > long press Save, which can be shared to moments for summary and optimization.

The difficulty lies in:

① converts canvas to base64 format, which will lead to cross-domain problems.

② async problem (painting is finished before the picture is loaded)

The problem of ③ background transparency and so on.

Optimization:

① definition: you can draw canvas into 2-4 times the image, convert it into an image, and compress it back to 50%, 25%.

② sharing map loading speed: Mini Program QR code, background image and other page loading stage can first request, click the share button to draw directly, reduce the request time is long lead to the problem of slow generation of painting, at the same time can also avoid QR code, background map loading is not completed, painting has started, resulting in the sharing picture drawn without background picture, QR code problem.

The above is all the content of the article "how to share screenshots using canvas". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report