React二维码组件
先看效果
ImageCode.js
import React, { Component } from 'react';
import styles from './index.less'
export default class ImageCode extends Component{
constructor(props){
super(props)
this.state = {
...this.initState(),
}
}
initState = () => {
return {
data: this.getRandom(109,48,4),
rotate: this.getRandom(75,-75,4),
fz: this.getRandom(8,20,4),
color: [
this.getRandom(100,255,3),
this.getRandom(100,255,4),
this.getRandom(100,255,3),
this.getRandom(100,255,3)
],
}
}
getRandom(max, min, num) {
const asciiNum = ~~(Math.random()*(max-min+1)+min)
if(!Boolean(num)){
return asciiNum
}
const arr = []
for(let i = 0; i < num; i++){
arr.push(this.getRandom(max, min))
}
return arr
}
canvas = () => {
const { getRandom } = this
const canvas = document.getElementById('bgi')
let ctx = canvas.getContext('2d')
canvas.height = canvas.height
ctx.strokeStyle = `rgb(${this.getRandom(100,10,3).toString()})`
for( let i = 0; i< 7; i++ ) {
ctx.moveTo(getRandom(200,0),getRandom(200,0))
ctx.stroke();
}
}
componentDidMount() {
this.refreshCode()
}
refreshCode = () => {
this.setState({
...this.initState(),
})
this.canvas()
}
render() {
const { rotate, fz, color } = this.state
let abcArr = [];
this.state.data.map((v, i) => {
let randomStr = String.fromCharCode(v > 57 && v < 84 ? v + 7 : ( v < 57 ? v : v + 13 ));
abcArr.push(randomStr);
})
// 传值给父组件
this.props.getImageCode(abcArr.join(''));
return (
<div className={styles.vcodewrap} onClick={this.refreshCode}>
<canvas className={styles.bgiview} id="bgi" width="200" height="200"></canvas>
{abcArr.map((letterStr, i) =>
<div
key={i}
className={styles.itemStr}
style={{
fontSize: `20px`,
fontWeight: 800,
color: `rgb(${color[i].toString()})`,
}}
>
{letterStr}
</div>
)}
</div>
)
}
}
ImageCode.less
.vcodewrap {
width: 90px;
overflow: hidden;
font-size: 20px;
height: 35px;
text-align: center;
position: relative;
background: #c5026e;
display: flex;
padding: 8px;
align-items: center;
justify-content: center;
cursor:pointer;
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Chrome/Safari/Opera */
-khtml-user-select: none; /* Konqueror */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently not supported by any browser */
.itemStr {
margin-left: 7px;
//margin-left: 3px
}
.mask {
position: absolute;
width: 100%;
height: 100%;
top: 0;
background-color: rgba(0,0,0,0.95) ;
opacity: 0.8;
line-height: 25px;
color: white;
z-index: 1;
}
.bgiview {
top: 0;
left: 0;
position: absolute;
width: 100%;
height: 100%;
}
}
使用方法
在index.js中使用
import React, { Component } from 'react';
import ImageCode from '../ImageCode'
export default class Index extends Component {
getImageCode = (value) => {
console.log(value.toLowerCase()); // 二维码结果
}
render() {
<div>
<ImageCode getImageCode={this.getImageCode} />
</div>
}
}