目录
画布的知识点
1、绘图(创建画布)
<canvas id = 'canvas' width='宽度',height=‘高度’>
2、获取画步
通过getElementById(canvas的id)
3、获取画笔
使用context对象
4、绘制直线
let ctx = canvas.getContext('2d')
ctx.beginPath() //设置起点
ctx.stroke() //设置终点
5、设置描边颜色
ctx.strokeStyle = '#fff'
6、设置闭合路径
closePath
ctx.beginPath()
ctx.moveTo(rn(0, w), rn(0, h))
ctx.lineTo(rn(0, w), rn(0, h))
ctx.strokeStyle = rc(0, 160);
ctx.closePath();
ctx.stroke();
7、填充路径
fill()
8、设置填充颜色
fillStyle = ‘颜色’
9、画弧线
arc(x,y,r,开始角,结束角),方向
x,y:确定圆心的坐标
r:表示圆形或弧形的半径
开始角:表示弧点的起始位置,通常用Math.PI表示(可以理解为180度)
结束角:表示弧点的结束位置
10、绘制矩形
rect(x,y,width.height)
x,y表示矩形左上角的坐标
ctx.fillStyle = rc(128,128)
ctx.fillRect(0,0,w,h)
11、绘制文本
context.fillText(text,x,y)
context.fillText(text,x,y)
context.fillStyle = 'red'
12、移当前的坐标系
context . translate(x,y)
13、设置坐标系的旋转角度
context.rotate(deg)
验证码制作
(1) 定义生成随机数的函数
- 随机颜色:随机生成 r,g,b
function rn (min,max){ //随机数函数
return parseInt(Math.random()*(max-min)+min)
}
function rc(min,max){ //随机颜色的函数
var r = rn(min,max)
var g = rn(min,max)
var b = rn(min,max)
return `rgb(${r},${g},${b})`
}
(2)设置绘制验证码的区域:矩形、浅色背景
var w = 120;
var h = 40;
var ctx = document.getElementById('canvas').getContext('2d')
ctx.fillStyle = rc(128, 128)
ctx.fillRect (0, 0, w, h)
(3) 随机产生字符串
var pool = 'abaahjffkhbvjkzvds'
let arr = [ ]
for(let i=0;i<4; i++){
var c= pool[ rn(0,pool.length)]
var fs = rn(18,40);
var deg = rn(-30,30);
ctx.font = fs +'px'
ctx.textBaseline = 'top' //设置文本的基线
ctx.fillStyle = rc(0,200)
ctx.save();
ctx.translate(30*i+15,15)
ctx.rotate(deg*Math.PI / 180)
ctx.fillText(c,-10,-15);
ctx.restore()
arr.push(c)
(4)随机产生5条干扰线,干扰线的颜色要浅一点
for (var i=0;i<5;i++){
ctx.beginPath()
ctx.moveTo(rn(0,w),rn(0,h))
ctx.lineTo(rn(0,w),rn(0,h))
ctx.strokeStyle = rc(0,160);
ctx.closePath();
ctx.stroke();
}
(5)随机产生40个干扰的小点
for(var i = 0; i< 40 ;i++){
ctx.beginPath()
ctx.arc(rn(0,w),rn(0,h), 1,0,,2*Math.PI) //随机确定圆心坐标
ctx.closePaht()
ctx.fillStyle = rc(0,200) //随机填充颜色
ctx.fill(); //进行填充