In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how to use JS to realize the gadget to generate the National Day thunder image. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
The techniques used here are:
HTML+ CSS+ JavaScript
Download.js library
Fabric.js library
Here is a screenshot of the gadget:
1. Page layout
I won't say much about this part, but go straight to the code:
This page is relatively simple, the outside is a large background image, in the middle is an avatar display box and template switch button, below is an upload button and a download button. After the page is laid out, the style is written. The CSS code is as follows:
Body,html {min-height: 100%; width: 100%; user-select: none; font-size: 18px;}. Wrapper {width: 100%; height: 100%; max-width: 620px; max-height: 800px; margin: 0 auto; background-image: url ('.. / img/bg.png'); background-repeat: no-repeat; background-size: 100%; padding-top: 13em } # export-img {display:none; margin:0 auto; width:250px; height:250px;} .main-box {display: flex; align-items: center; justify-content: center;} .main-box .next, .main-box .prev {background-image: url ('.. / img/next.png'); background-size: contain; border-radius: 50%; width: 2.275rem Height: 2.275rem}. Main-box .prev {transform: rotate (180deg)} .main-box. Main-img {margin: 0.75rem; background: # fff; border: .25rem solid # fbe6b5; border-radius: .75rem; font-size: 0} # content {border-radius: .5rem; position: relative; width: 9.5remm; height: 9.5remm; margin-left: 50% Transform: translateX (- 50%); overflow: hidden}. Operation-btns {display: flex; align-items: center; justify-content: center; flex-direction: column; margin-top: .75rem} .operation-btns. Upload-btn {width: 11.6; height: 3.6; background-size: 100% Background-image: url ('.. / img/upload.png')}. Operation-btns. Export-btn {display: none; width: 11.6; height: 3.75; background-size: 100% 100%; background-image: url ('.. / img/export.png')}
This is just a simple implementation, for reference only. There are a lot of places that can be optimized, which are not modified here, and those who are interested can be customized by themselves.
two。 Picture upload and display
Then there is the implementation of the logic part. First, there are several global variables that need to be defined first, which will be used later:
Let canvasFabric; / / canvas instance let hat = "hat0"; / / current template classlet hatInstance; / / template layer instance const screenWidth = document.getElementById ("content") .height of the content box
Then you need to process the uploaded image and display it on the page:
Function viewer () {/ / get the uploaded image file const file = document.getElementById ("upload"). Files [0]; / / get the tag const img = document.getElementById ("img") that needs to display the image; / / create a file to read the file object const reader = new FileReader (); if (file) {/ / convert the file to Base64 reader.readAsDataURL (file) / / trigger reader.onload = () = > {/ / assign the url of base64 to the tag img.src = reader.result; / / when the image is loaded successfully and trigger img.onload = () = > img2Cvs (img);}} else {img.src = ""}}
The FileReader object of HTML5 is used here, which provides a method to read the file and an event model that contains the result of the read. You can use new to initialize the object, and the FileReader object contains four methods, three of which are used to read the file and one to interrupt the read. It is important to note that whether the read succeeds or fails, the method does not return the read result, which is stored in the result property. The readAsDataURL method is used here, and MDN introduces this method as follows:
The readAsDataURL method reads the specified Blob or File object. When the read operation is complete, the readyState becomes a completed DONE and the loadend (en-US) event is triggered, while the result property contains a string (base64 encoding) in data:URL format to represent the contents of the read file.
In other words, the uploaded image is converted into a URL in Base64 format, and a value is assigned to the tag that displays the image, so that the tag displays the avatar, and the effect is as follows:
This completes the upload and display of the picture, and then it's time to initialize a canvas.
3. Initialize the canvas
Img.load is executed at the end of the above code, where the onload event is executed immediately after the image is loaded. After the image display is complete, the img2Cvs method is executed, which is mainly used to initialize a canvas and show and hide some elements of the page.
The fabric library is used in the img2Cvs method, and Fabric.js is a library that simplifies Canvas programming. Fabric.js provides Canvas with the missing object model, svg parser, interaction, and a set of other indispensable tools. Canvas provides a good canvas capability, but Api is not friendly enough. Fabric.js is developed for this purpose, it is mainly to write code in the way of objects. What Fabric.js can do is as follows:
Create and fill graphics (including pictures, text, regular graphics, and complex paths that make up graphics) on Canvas.
Fill the graph with a gradient color.
Combined graphics (including combined graphics, graphic text, pictures, etc.).
Set up graphic animation set user interaction.
Generate JSON, SVG data, etc.
The generated Canvas object comes with drag-and-drop functionality.
You can install the fabric.js library through the npm command:
Npm install fabric-save
You can also refer to it through cdn:
Let's look at how the img2Cvs method is implemented:
Function img2Cvs (img) {/ / gets and displays the canvas canvas and sets the size of the canvas to the size of the picture const cvs = document.getElementById ("cvs"); cvs.width = img.width; cvs.height = img.height; cvs.style.display = "block" / / create a canvas and set its location and background image canvasFabric = new fabric.Canvas ("cvs", {width: screenWidth, height: screenWidth, backgroundImage: new fabric.Image (img, {scaleX: screenWidth / img.width, scaleY: screenWidth / img.height})}); / / switch template changeHat () / / hide the upload picture button and display the download picture button document.getElementsByClassName ("upload-btn") [0] .style.display = "none"; document.getElementsByClassName ("export-btn") [0] .style.display = "block";}
The fabric.Canvas () method has two parameters, the first parameter is the id of the canvas canvas, and the second parameter is the configuration item when initializing the canvas. Here we set the initial canvas size and the background image, using the avatar we uploaded as the background image. The background image here is the instantiated fabric.Image object, and the first parameter when the object is initialized is the picture object, and the second parameter is the picture styling configuration object.
When you have created the canvas, you need to switch out the first template, hide the upload picture button, and display the download avatar button. In this way, the first step of the work is completed. Let's take a look at how to switch existing templates.
4. Switch template
Next, let's take a look at how switching templates are implemented:
Function changeHat () {/ / hides the current template document.getElementById (hat). Style.display = "none"; / / get all templates const hats = document.getElementsByClassName ("hide"); hat = "hat" + (+ hat.replace ("hat", ") + 1)% hats.length; / / get the current template and display const hatImage = document.getElementById (hat); hatImage.style.display =" block " / / if a layer currently exists Remove if (hatInstance) {canvasFabric.remove (hatInstance)} / / add the current template as layer object hatInstance = new fabric.Image (hatImage, {top: 0, left: 0, scaleX: screenWidth / hatImage.width, scaleY: screenWidth / hatImage.height, cornerColor: "# 0b3a42", cornerStrokeColor: "# fff", cornerStyle: "circle", transparentCorners: false RotatingPointOffset: 30}) / / set layer objects to non-stretchable hatInstance.setControlVisible ({mt: false, mb: false, ml: false, mr: false, bl: false, br: false, tl: false, tr: false, mtr: false,}) / / add layers to the canvas canvasFabric.add (hatInstance);}
By default, the fabric.js element has eight points to scale any object. Here, we do not want users to stretch the fabric object horizontally or vertically. We can set it not to stretch through the setControlsVisibility () method. This method needs to pass in a configuration object, which contains eight scaling points, all of which can be set to false.
Finally, we add the layer generated by the template to the canvas. Here we use the add method, which is the event provided by fabric. Here are the common events provided by fabric.js:
Object:added add layer
Object:modified Editing layer
Object:removed remove layer
Selection:created first selected layer
Selection:updated layer selection change
Selection:cleared clear layer selected
5. Output picture
After the above steps, we initialize a canvas. The background of the canvas is the picture we uploaded. There is also a layer on the canvas, which is the template of our choice. The final step is to output the composite image. Let's see what happens when you click the download image button:
Function exportFunc () {/ / hide the selection box, upload / download button, canvas canvas document.getElementsByClassName ("main-box") [0] .style.display = "none"; document.getElementsByClassName ("operation-btns") [0] .style.display = "none"; document.getElementById ("cvs"). Style.display = "none"; / / generate URL from the canvas and assign values to the corresponding tags to display const exportImage = document.getElementById ("export-img") ExportImage.style.display = "block"; exportImage.src = canvasFabric.toDataURL ({width: screenWidth, height: screenWidth}); / / download the generated image window.confirm ("do you want to download avatar")? Download (exportImage.src, "National Day thunder", 'image/png'): void 0}
Here we use the toDataURL method to generate a picture of the canvas instance object, which is the method of the fabric object, and you can export the canvas as a picture, exporting a URL in Base64 format. In this way, the img tag can get the URL and display the final image.
Finally, added an optional function, that is, download the generated avatar, here used the download.js library, the first parameter of this method is the URL of the picture, the second parameter is the name of the downloaded picture, and the third parameter is the format of the picture.
This is all the functions of this mini application, just a simple implementation, there is also a BUG, mainly provides an implementation idea. I have never come into contact with the concept of canvas and canvas before, and this time I have increased my knowledge.
Thank you for reading! On "how to use JS to generate the National Day thunder image of the gadget" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, you can share it out for more people to see it!
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.