HTML
<canvas id="canvas" width="120" height="40"></canvas>
Javascript
var canvas = document.getElementById("canvas")
var context = canvas.getContext("2d")
draw()
canvas.onclick = function () {
context.clearRect(0, 0, 120, 40)
draw()
}
function getColor() {
// 0 - 255之间的随机数
var r = Math.round(Math.random() * 255)
var g = Math.round(Math.random() * 255)
var b = Math.round(Math.random() * 255)
return `rgb(${r},${g},${b})`
// return "rgb(" + r + "," + g + "," + b + ")"
}
function draw() {
context.strokeRect(0, 0, 120, 40)
//随机绘制8条直线, 起始坐标 在矩形任何区域, 结束坐标在矩形任何区域
for (var i = 0
context.beginPath()
context.moveTo(Math.random() * 120, Math.random() * 40)
context.lineTo(Math.random() * 120, Math.random() * 40)
context.strokeStyle=getColor()
context.stroke()
}
//20个小点, 颜色随机
for (var i = 0
context.beginPath()
var x = Math.random() * 120
var y = Math.random() * 40
context.arc(x,y,1,0,360 * (Math.PI/180))
context.fillStyle=getColor()
context.fill()
}
var aCode = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for (var i = 0
context.save()
var x = 20 + i * 20
var y = 20 + 10 * Math.random()
var index = Math.floor(Math.random() * aCode.length)
var txt = aCode[index]
context.font = "bold 25px 微软雅黑"
context.fillStyle=getColor()
//水平和垂直方向的位移
context.translate(x,y)
//对文字的旋转
var deg=90*Math.random()* (Math.PI/180)
context.rotate(deg)
//写入文字
context.fillText(txt, 0, 0)
context.restore()
}
}