<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>随机生成矩形</title>
</head>
<body>
<!--canvas就是提供了一块区域-->
<canvas id="canvas" width="800" height="500"></canvas>
<script type="text/javascript">
//获取canvas的id
var canvas = document.getElementById("canvas");
//定义一个二维绘图方式,用context来接收
var context = canvas.getContext("2d");
//封装一个函数
function fun(){
//定义x轴,y轴,宽高,rgb颜色的随机值
var x = Math.floor(Math.random() * 1000);
var y = Math.floor(Math.random() * 600);
var w = Math.floor(Math.random() * 500);
var h = Math.floor(Math.random() * 300);
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
//清除像素,相当于恢复初始值
context.clearRect(0,0,800,500)
//字符串拼接的方式设置颜色
context.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
//绘制矩形
context.fillRect(x,y,w,h);
}
//利用定时器隔一秒刷新
setInterval(fun,1000)
</script>
</body>
</html>
随机生成矩形
最新推荐文章于 2022-06-09 22:18:08 发布