文章目录
- 前言
- 效果
- 代码
前言
这是一个前端随机生成图片的组件,可以用作滑块验证组件的背景图。
效果
- 以下效果是结合滑块验证组件一起构建的。
代码
<template>
<img ref="random-image" />
</template>
<script>
export default {
name: "RandomImg",
props: {
width: {
type: Number,
default: 400
},
height: {
type: Number,
default: 220
}
},
mounted() {
this.init()
},
methods: {
// 生成随机颜色
getRandomColor() {
const r = Math.floor(Math.random() * 255)
const g = Math.floor(Math.random() * 255)
const b = Math.floor(Math.random() * 255)
const a = Math.random()
const color = `rgba(${r}, ${g}, ${b}, ${a})`
return color
},
// 生成随机图案
getRandomPattern(ctx) {
const random = Math.floor(Math.random() * 3 + 1)
if (random == 1) {
const rectr = Math.floor(Math.random() * 2)
const rectx = Math.floor(Math.random() * this.width)
const recty = Math.floor(Math.random() * this.height)
const rectwidth = Math.floor(Math.random() * this.width)
const rectheight = Math.floor(Math.random() * this.height)
if (rectr == 0) {
ctx.beginPath()
ctx.strokeStyle = this.getRandomColor()
ctx.strokeRect(rectx, recty, rectwidth, rectheight)
ctx.closePath()
} else {
ctx.beginPath()
ctx.fillStyle = this.getRandomColor()
ctx.fillRect(rectx, recty, rectwidth, rectheight)
ctx.closePath()
}
} else if (random == 2) {
var arcr = Math.floor(Math.random() * 2)
var arcx = Math.floor(Math.random() * this.width)
var arcy = Math.floor(Math.random() * this.height)
var arcr = Math.floor(Math.random() * this.height)
if (arcr == 0) {
ctx.beginPath()
ctx.strokeStyle = this.getRandomColor()
ctx.arc(arcx, arcy, arcr, 0, 2 * Math.PI, false)
ctx.stroke()
ctx.closePath()
} else {
ctx.beginPath()
ctx.fillStyle = this.getRandomColor()
ctx.arc(arcx, arcy, arcr, 0, 2 * Math.PI, false)
ctx.fill()
ctx.closePath()
}
} else if (random == 3) {
var movex = Math.floor(Math.random() * this.width)
var movey = Math.floor(Math.random() * this.height)
var linex = Math.floor(Math.random() * this.width)
var liney = Math.floor(Math.random() * this.height)
var linew = Math.floor(Math.random() * this.height / 5)
ctx.beginPath()
ctx.strokeStyle = this.getRandomColor()
ctx.moveTo(movex, movey)
ctx.lineTo(linex, liney)
ctx.lineWidth = linew
ctx.stroke()
ctx.closePath()
}
return ctx
},
// canvas转image
canvasToImage(cvs) {
const imgDom = this.$refs['random-image']
imgDom.src = cvs.toDataURL('image/png')
},
// 初始化
init() {
const canvas = document.createElement('canvas')
canvas.width = this.width
canvas.height = this.height
let context = canvas.getContext('2d')
context.fillStyle = '#ccc'
context.fillRect(0, 0, this.width, this.height)
for (let i = 0; i < 10; i++) {
context = this.getRandomPattern(context)
}
this.canvasToImage(canvas)
},
// 刷新图片
refresh() {
this.init()
}
}
}
</script>
<style scoped>
* {
user-select: none;
}
</style>