In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces canvas how to achieve multiple picture editing related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe you will have something to gain after reading this canvas how to achieve multiple picture editing articles, let's take a look at it.
Product requirements for picture editor
First of all, as it involves the project development of the actual company, the picture editor that meets the demand may just edit a single picture, or it may give you a list of pictures, that is, the editing of multiple pictures, before the user saves it, the user can switch back and forth which picture to edit now, and remember that the editing operation of each photo should be allowed to be undone, and finally click the Save button. Unedited images will be discarded and edited pictures with graffiti will be uploaded to the server.
Preparation work, the relevant knowledge points that must be understood
The use of html2canvas
Html2canvas is a plug-in that actually converts ordinary html elements on a web page into canvas. So why convert html elements to canvas? That's because canva has many features that html elements don't have, such as drawing on canvas, drawing lines, and so on, and canvas directly provides api to guide the content displayed on the canvas into pictures. Is it a bit like a screenshot? html2canvas takes advantage of this. When I first used html2canvas, I had a tablet project in the company's H6 project. You need to sign in the handwriting board, then export the signed picture and upload it. Later, there is a project of a picture editor on the web side, which uses the plug-in html2canvas. Let's introduce the plug-in below.
Introduction
Disadvantages of html2canvas:
The canvas converted with html2canvas does not restore the original elements 100% in the final visual effect, that is, some pixels will be lost.
Installation of html2canvas:
Npm install html2canvas
Introduction of html2canvas:
Import html2canvas from 'html2canvas'
The use of html2canvas
If a html element with an image (whether img tag or background image) is converted to canvas, the img or background image in the generated canvas is missing and becomes a white background, and the console tells you that the image is cross-domain. The solution is as follows:
The first item below must be satisfied, and then the second and third add different configuration items based on whether the html element is an img tag or a background image.
1. The picture server configures Access-Control-Allow-Origin or uses a proxy
Configure useCORS:true in the configuration item of 2.html2canvas
Add crossOrigin='anonymous' to 3.img tag
Convert html to canvas, and solve the cross-domain problem of images:
Html2canvas (dom, {useCORS: true, / / background image cross-domain scale: window.devicePixelRatio,// pixel ratio width: dom.offsetWidth height: dom.offsetHeight}) .then (canvas = > {/ / get base64 let base64 = canvas.toDateUrl ()})
Because html2canvas converts ordinary html to canvas, while canvas has its own method of converting itself into base64, base64 format files can be displayed on the page directly as the src of img tags:
At this point, if you want to upload the generated image, base64 cannot upload it directly. You need to convert base64 to blob format. So it is as follows: we pass the base64 data into the base64ToBlob function, and the final function return results in blob data. Please note: this method is simply a general method for converting base64 to blob.
Base64 to blob
Function base64ToBlob (base64) {var arr = base64.split (','), mime = arr [0] .match (/: (. *?); /) [1], bstr = atob (arr [1]), n = bstr.length, u8arr = new Uint8Array (n); while (NMAE -) {u8arr [n] = bstr.charCodeAt (n);} return (new Blob ([u8arr], {type: mime}))}
In fact, canvas has its own method to convert canas to blob object.
Canvas to blob
Canvas.toBlob (file= > {/ / at this point file is the blob data format. / / after successfully uploading to blob, you need to add a name attribute to the blob data, otherwise an error will be reported later when uploaded to the server: size not set file.name = 'cover.png'})
However, in the actual project development, we encountered that the canvas element in some low-version mobile browsers does not support the toBlob method and reported an error toBlob is not a function. So at this point, we need to polyfill browsers that do not support the canvas.toBlo method.
The DOM canvas element exposes the HTMLCanvasElement interface, which provides properties and methods for manipulating the layout and rendering of an canvas element. The HTMLCanvasElement interface inherits the properties and methods of the element interface. (from MDN)
ToBlob method compatibility writing method
If (! HTMLCanvasElement.prototype.toBlob) {Object.defineProperty (HTMLCanvasElement.prototype, 'toBlob', {value: function (callback, type, quality) {var binStr = atob (this.toDataURL (type, quality) .split (',') [1]) var len = binStr.length var arr = new Uint8Array (len) for (var I = 0; I
< len; i++) { arr[i] = binStr.charCodeAt(i) } callback(new Blob([arr], { type: type || 'image/png' })) } })} 以上代码判断当前浏览器HTMLCanvasElement.prototype内是否含有toBlob方法,如果没有该方法,则为HTMLCanvasElement.prototype添加toBlob方法。 到目前为止,无论是base64直接转成blob,还是canvas直接转成blob,最后目的都是为了将blob数据上传到服务器。请注意:当前页面的blob数据是存储在缓冲区的,而不是像电脑本地文件存储在硬盘中上传那样,所以需要添加 isLocalFile:false属性,fileData属性接收一个数组,如果是一张图片,则是个长度为1的,元素为blob格式的数组。上传文件到服务器在这里不做介绍。 提交blob到服务器 // 转完图片数据,提交服务器 async upload (blobArr) { const oss = await this.$uploadOSS.init({ fileData: blobArr, isLocalFile: false, onProgress: percent =>{}, onSuccess: (res) = > {console.log (res)}}) if (oss) {const data = await oss.start () if (! data.code) {this.$message.error (data.message)}
The above is an introduction to the common properties of html2canvas and canvas, as well as a prerequisite for the development of a picture editor. The following will describe in detail step by step in the existing canvas graffiti board on the basis of the development of multiple image editor ideas and process.
How to do the picture editor based on canvas?
1. Since you want to edit a picture, naturally you have to provide us with the address of the picture, which may be a local relative path, a remote address, or one or more pictures. So the data structure for operation is an array. If there is only one picture, it is an array with a length of 1, and the element is an array of image addresses. In addition, you need to solve the cross-domain problem of the picture to avoid the graffiti part of the generated picture. If the background is white, the avatar or the picture is missing, a detailed solution has been provided above.
2. The picture editor must be a universal component, so fill in a two-dimensional array of the same length according to an array of length length of the picture src passed by the parent component. The elements in the two-dimensional array record the history of each picture being edited, that is, the base64 data generated each time the canvas is operated. The image is populated with an empty array [] by default when initializing before editing. Here we introduce a good method for filling an array, fill. It is worth noting that if the content of fill is a reference type, every item of fill will be the same reference, and all the other elements will be changed when you manipulate one of the elements.
/ / result: [[], [],...] this.canvasArrBase = Array (length) .fill (0) .map (item = > {return []})
2, click on a different picture, send the src of the picture into the editor component, and take the src as the canvas background image, at this time you can see a picture visually, in fact, a background picture of canvas in dom is src.
3. Start doodling the canvas on the page. In order to avoid being unable to use canvas graffiti or image editor on touch screen devices such as surface, please use the touch event instead of the mouse event.
/ / start drawing canvas.addEventListener ('touchstart', e = > {...}, false) / / drawing canvas.addEventListener (' touchmove', e = > {...}, false) / / end drawing canvas.addEventListener ('touchend', e = > {...}, false)
4. Before entering the picture editor, you will click on the index of the picture and the picture array where the picture is located, and pass it into the picture editor as props. Remember which picture currentIndex you are currently editing, so that you can record graffiti or undo operations on this picture. Every time the user operates on the canvas, that is, starting touchstart, then touchmove, and finally touchend, the content of the current canvas canvas (all content, not just the graffiti). Similar to each submission of git, git will generate a snapshot of the entire project even if only one line of code is submitted, instead of just recording the modified line of code, git rollback is the rollback of the snapshot), including this background image using canvas.toDateUrl () to generate base64 and push it into the this.canvasArrBase [current Index] introduced above, when the currenIndex array has one more history image. That is, the picture of graffiti has been preserved by us. This is the canvas image editor, the basis of undo, with which we know what to show after undo.
/ / the snapshot generated by the new graffiti operation is stored in the array of the current index this.canvasArrBase [this.currentIdex] .push (canvas.toDataUrl ())
5. Switching pictures means changing the background of the canvas, changing the currentIndex, and then editing another picture on the new currentIndex. In fact, it is the same step, nothing more than all the contents just shown on the push canvas of the currently edited picture.
6. Here comes the point. How to undo it? How to undo, how to undo step by step on the canvas and see the last, last painting record?
As each picture is edited, each picture produces some history, which we use to roll back and undo. When we click to undo one of the currently edited images, we need to draw the contents of the canvas shown in the last canvas into the current canvas. When undoing, you can delete our stored data source directly, so you only need to use the canvas.drawImage () method to draw the record that needs to be displayed into the canvas canvas.
The drawImage method has many parameters. Click the usage to view the details.
Let newBaseArr = this.canvasArrBase [this.currentIdex] let {offsetWidth: canvasWidth, offsetHeight: canvasHeight} = canvas// generate a new picture let image = new Image () / / the src of the picture is assigned to the value of the base64 that needs to be displayed (that is, let the user see the undone screen) image.src = this.canvasArrBase [this.currentIdex] [newBaseArr.length-1] / / load the image using onload listening after assigning to the src of CanvasArrBase After the loading is completed, it is very likely that the drawing will fail without onload. Image.onload = function () {canvas.drawImage (image, 0,0, canvasWidth, canvasHeight)}
7. Performance optimization: since you have no idea how big a picture the user will take to edit it, if you have 9 pictures and each picture is edited 10 times, the amount of base64 data in memory will be very large, which may cause stutters in the page during page switching or picture graffiti history revocation, in order to avoid this situation, before switching pictures. I will only store the base64 of the last picture in the current picture.
8. Submit and judge the length of each item in the this.canvasArrBase before saving. If it is greater than 0, it has been edited, otherwise it will be filtered out. Then use the previous upload method to upload to the server, on the OK!
This is the end of the article on "how to edit multiple pictures in canvas". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to edit multiple pictures in canvas". If you want to learn more, you are 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.