随机的圆,直线,矩形。随机的空心、实心、长度,大小、颜色
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.canvas {
border: 2px solid yellow;
box-shadow: 0.5px 0.5px 10px 5px pink;
display: block;
margin: 0 auto;
}
.btn {
width: 200px;
height: 100px;
color: gold;
background-color: black;
margin: 20px auto;
text-align: center;
line-height: 100px;
cursor: pointer;
font-family: "楷体";
font-size: 40px;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas class="canvas" width="900" height="600"></canvas>
<div class="btn">随机生成</div>
<script>
// 随机产生一种图形 0 1 2
var canvas = document.querySelector(".canvas");
var context = canvas.getContext("2d");
var btn = document.querySelector(".btn");
// 第一步随机 随机图形
btn.onclick = function () {
context.clearRect(0, 0, 900, 600);
var grap = Math.floor(Math.random() * 3);
if (grap == 0) {
creatyuan();
} else if (grap == 1) {
creatrect();
} else if (grap == 2) {
creatline();
}
};
// 公用函数 颜色 x y
function show() {
var x = Math.floor(Math.random() * 900);
var y = Math.floor(Math.random() * 600);
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var a = Math.random();
var obj = {
x: x,
y: y,
bg: "rgba(" + r + "," + g + "," + b + "," + a + ")",
};
return obj;
}
// 制作圆的函数
function creatyuan() {
var cr = Math.floor(Math.random() * 300);
var obj = show();
var str = Math.floor(Math.random() * 2);
context.beginPath();
context.arc(obj.x, obj.y, cr, 0, Math.PI * 2);
if (str == 1) {
context.fillStyle = obj.bg;
context.fill();
} else {
context.strokeStyle = obj.bg;
context.stroke();
}
context.closePath();
}
// 制作矩形的函数
function creatrect() {
var obj = show();
context.beginPath();
var width = Math.floor(Math.random() * 900);
context.font = width + "bold";
var str = Math.floor(Math.random() * 2);
if (str == 1) {
context.fillStyle = obj.bg;
context.fillRect(obj.x, obj.y, obj.x, obj.y);
} else {
context.strokeStyle = obj.bg;
context.strokeRect(obj.x, obj.y, obj.x, obj.y);
}
context.closePath();
}
// 制作直线的函数
function creatline() {
var obj = show();
// 开始
context.beginPath();
var length = Math.floor(Math.random() * 10);
var x = Math.floor(Math.random() * 900);
var y = Math.floor(Math.random() * 600);
context.moveTo(x, y);
context.lineTo(obj.x, obj.y);
context.strokeStyle = obj.bg;
context.lineWidth = length;
// 画直线
context.stroke();
// 结束
context.closePath();
}
</script>
</body>
</html>