The development of the interesting gif animation platform development (2)

Wonderful review

Preface

I have previously developed a GIF generation platform in my spare time. The specific development background I also introduced in the previous article to teach you a gif production platform that can generate vibrato style GIFs. Let’s continue to implement it today. The implementation of this platform and the gif animation platform will be completely implemented by front-end means, so you will find many interesting front-end plug-ins in the following content. Next, let's take a look at the main functions to be implemented:

  • Pure front end realizes image upload and preview

  • Free drag sorting of elements based on react-beautiful-dnd

  • Use javascript to realize the function of generating uuid

  • Use file-saver to download files from the front end

  • Use gif.js to generate gif animation based on pictures

  • Method for controlling playback speed of gif animation

text

Still in accordance with the author's usual style, before implementing the function, let's take a look at the preview effect after implementation: 

 It can be seen from the renderings that we only need to upload a sequence of pictures to dynamically generate gif animations, and right-click to save the gif files. We can also control the playback speed and arrangement order of the animations for more flexible configuration of the animations. If If you want to experience it yourself, you can go directly in the following ways:

Online address: http://io.nainor.com/qt

1. Basic page setup

Before we start, we must first clarify the basic page structure. The author is divided into the following structure:   From the above figure, it is divided into 3 areas. We can use any third-party components we are familiar with to achieve it. The author uses antd to develop here. The technical plan diagram is as follows: The   above is the approximate realization goal analyzed by the author, and it is also a commonly used development map by the author. The goal orientation is still very helpful to the improvement of development efficiency. The author suggests that you can also think first before realizing more complex business requirements. Scheme, and then code.

2. Realize image upload and preview function

For the first step of the interface, I think everyone can realize it. We will now implement it step by step to the realization of the function. Let's first realize the upload and preview of the image. Since we do not use the server here, the image preview is completely realized by the front-end method, so We need to use the FileReader object.

The FileReader object allows a Web application to asynchronously read the contents of a file (or raw data buffer) stored on the user's computer. Use a File or Blob object to specify the file or data to be read.

The File object can be a FileList object returned after the user selects a file on an input element, or a DataTransfer object generated by a drag-and-drop operation, or it can be a result returned by executing the mozGetAsFile() method on an HTMLCanvasElement. Next, let's see how to use antd's Upload component and FileReader to achieve image preview. The specific code is as follows:

const uploadprops = useMemo(() => ({
    name: 'file',
    multiple: true,
    listType:"picture-card",
    onPreview: () => {},
    showUploadList: false,
    beforeUpload(file, fileList) {
      // 解析并提取excel数据
      let reader = new FileReader();
      reader.onload = function(e) {
        let url = e.target.result;
        setImageList(prev => [...prev, {id: uuid(6, 16), url}])
      };
      reader.readAsDataURL(file);
    }
  }), []);

uploadprops is the property configuration required by the Upload component. Through the code, we can know that we intercepted the image in the beforeUpload stage, and converted the read file into a base64 address through the readAsDataURL API of the FileReader object, so that we can display it in the following way Pictured:

<img src={item.url} id={item.id} alt=""/>

In the code, we store the image data in an object. The object includes the unique id and url generated by the uuid function. As for why the unique id is generated, the author will introduce it below.

3. Use react-beautiful-dnd to realize free drag sorting of elements

After studying H5-Dooring | a powerful open source H5 editor, you will find that the react-dnd module is very familiar, because the open source editor uses the component drag and component data transfer implemented by react-dnd. The author found a more interesting drag-and-drop library react-beautiful-dnd in the community, which can also achieve elegant and smooth intelligent drag-and-drop effects. The basic case is as follows:   After studying the library in depth, the author found that it can be directly used to implement image components. The function of dragging and sorting, so the author directly uses the library to encapsulate our picture components. Since the use of the library has detailed case codes, I will not introduce them in detail here, only need to mention that in order to achieve sorting, we It is necessary to determine the unique identifier of each element, so here I think of uuid, so the array data structure of the rendered image can be as long as this:

const imgList = [
	{
    	id: uuid(6, 10),
        url: '图片的base64位地址'
    }
]

In order to limit the image upload size, we can also limit the image upload size in the beforeUpload stage of the Upload component, which depends on the use. There are many ways to implement uuid. Here is an implementation method:

// 生成uuid
function uuid(len: number, radix: number) {
  let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  let uuid = [],
    i;
  radix = radix || chars.length;

  if (len) {
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
  } else {
    let r;
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';

    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16);
        uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r];
      }
    }
  }

  return uuid.join('');
}

The effect after the implementation is as follows:   As for the method of deleting the picture, it is also very simple. Use the unique id of the picture to delete it using the fiter method of the array in the array.

4. How to control the playback speed of GIF

We can use the slider component to control the playback speed of gif. gif.js also provides a speed interface. We only need to calculate the speed value. We all know that the longer the slider slides, the larger the value, and the corresponding The higher the speed, the smaller the time interval, so the display effect we designed in the front-end layer is as follows: the   maximum value of the slider is set to 20 and the minimum value is 1, correspondingly, when the slider is set to the maximum value, the playback speed of gif is the maximum , The dwell interval of each picture is 0.1s, and when the slider is at the minimum value of 1, the gif playback speed is the smallest, and each picture stays for 2s. According to this rule, we get the following rule: 

The specific code is as follows:

const handleSpeed = (v) => {
  let realSpeed = (20 - v + 1) / 10;
  setSpeed(realSpeed)
}

Of course, you can do it in a simpler way, and the slider component also provides reverse value operations.

5. Generate gif animation based on image sequence

The way to generate gif based on the picture sequence is also very simple. We get the pictures in the picture drag area in batches, assemble them into an array and send them to gif.js. Let’s see the effect directly: 

6. Use file-saver to download files from the front end

We only need to pass the generated gif image to the file-saver module, and use the API provided by it to download the file. This is also introduced by the author in the previous article, here is the code directly:

import { saveAs } from 'file-saver';

// resultImage为gif生成的gif图片对象
saveAs(resultImage, `${uuid(6, 10)}.gif`);

At last

If you want to learn more H5 games, webpack, node, gulp, css3, javascript, nodeJS, canvas data visualization and other front-end knowledge and actual combat, welcome to study and discuss together in "Interesting Frontend" to explore the front-end boundary together.

Guess you like

Origin blog.csdn.net/KlausLily/article/details/109759556