Home > Article > Web Front-end > Create your own digital rain avatar with canvas and gif.js
This article mainly introduces the sample code for creating your own digital rain avatar using canvas+gif.js. The detailed code is compiled here, which is of great practical value. Friends who need it can refer to it. I hope it can help everyone.
Instructions
1. Pass an avatar you like, and the last one is square
2. After generation, check whether the character color is too weird. You can change the character color
3. If you are satisfied, right-click and save as
gif.js
Today’s protagonist is gif.js. Gif.js is a library that relies on H5api to animate gifs on the browser. Here I will introduce the pitfalls I guess. Regarding drawing digital rain, there are related articles in the garden, so I won’t be blind.
gif.js can easily get gif based on canvas animation:
//代码来自官网 var gif = new GIF({ workers: 2,//启用两个worker。 quality: 10//图像质量 });//创建一个GIF实例 // 核心方法,向gif中加一帧图像,参数可以是img/canvas元素,还可以从ctx中复制一帧 gif.addFrame(imageElement); // or a canvas element gif.addFrame(canvasElement, {delay: 200});//一帧时长是200 // or copy the pixels from a canvas context gif.addFrame(ctx, {copy: true}); gif.on('finished', function(blob) {//最后生成一个blob对象 window.open(URL.createObjectURL(blob)); }); gif.render();//开始启动
Overall, the API of this library is very simple and friendly. I saw a jsGif before, and it was confusing, but later I discovered such a good thing. Since generating gif images is a CPU-intensive operation, especially when the images are large, the library allows rendering in a webworker. However, there are still a few points that need to be noted in the document (actually I stepped on the pitfalls):
1.git.addFrame is to add a frame. To generate a moving gif, a loop is required:
for(...){ gif.render(...) }
2. In the options of the constructor GIF, the workerScript option is required, so that the image can be rendered in the worker, as shown below:
var gif = new GIF({ workers: 2, quality: 10, workerScript:'./gif.worker.js' });
Have you learned it yet? Hurry up and try it out.
Related recommendations:
How to upload an avatar in the WeChat applet
An elegant method to use Laravel to generate a Gravatar avatar address
CSS3 implementation of avatar rotation effect example sharing
The above is the detailed content of Create your own digital rain avatar with canvas and gif.js. For more information, please follow other related articles on the PHP Chinese website!