In the React project, the interesting small plug-ins used such as: dynamic typing effect , background particle effect, draw a four-digit verification code with canvas in css5
1. Dynamic typing effect
A js method is encapsulated, which can be used at any time, without further ado, just read the source code directly
test.js file code
expotr const dz=(参数a,参数b)=>{ //使用ES6的箭头函数,a,b参数是前台视图层传过来的
let str = b,timer=0,i=0;
funcition typeing(){
if(i<=str.lenght){
a.innerHtml = str.slice(0,i++)+'_'
timer = setTimeout(typeing,200)
}
{
a.innerHtml = str
clearTimeout(timer)
}
}
return typeing() //返回typeing
}
View layer code test.jsx
import React, { Component } from 'react'
import {dz} from './../../js/test.js' //引入test.js文件,使用里面的dz方法
dz=()=>{
let id = document.getElementById("test")
let str = "打工人,打工魂"
dz(id,str) //使用js里面的方法
}
render
(
{
<div id="test"></div>
<button onClick={()=>{this.dz()}}>点击</button>
}
)
2. Background particle effect
First look at the renderings
Install directly with npm npm
install
--save particles-
bg //不懂什么意思的去百度吧~
import Particles from 'particles-bg' //引用刚才安装的插件
render
(
{
<Particles type="circle" bg={true}/> //type属性貌似还有lines circle...
}
)
3. Canvas draws a four-digit verification code in css5
There is a requirement in the project that requires a four-digit verification code. After thinking about it, I made one with canvas
First look at the html code
<canvas onClick={this.createCode} width="80" height='39' ref={el => this.canvas = el}/>
//canvas容器
The end is the js code
// 生成验证码
createCode = () => { //用的是es6中的箭头函数
const ctx = this.canvas.getContext('2d')
const chars = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
let code = ''
ctx.clearRect(0, 0, 80, 39)
for (let i = 0; i < 4; i++) {
const char = chars[randomNum(0, 57)]
code += char
ctx.font = randomNum(20, 25) + 'px SimHei' //设置字体随机大小,randomNum方法是写了一个取随机数的方法
ctx.fillStyle = '#D3D7F7'
ctx.textBaseline = 'middle'
ctx.shadowOffsetX = randomNum(-3, 3)
ctx.shadowOffsetY = randomNum(-3, 3)
ctx.shadowBlur = randomNum(-3, 3)
ctx.shadowColor = 'rgba(0, 0, 0, 0.3)'
let x = 80 / 5 * (i + 1)
let y = 39 / 2
let deg = randomNum(-25, 25)
/**设置旋转角度和坐标原点**/
ctx.translate(x, y)
ctx.rotate(deg * Math.PI / 180)
ctx.fillText(char, 0, 0)
/**恢复旋转角度和坐标原点**/
ctx.rotate(-deg * Math.PI / 180)
ctx.translate(-x, -y)
}
this.setState({
code //code是变量,我是在react中写,所有用的是setState
})
}
Look at the randomNum function method
export function randomNum(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
//min,max是参数,把结果return出去
The renderings are as follows