js代码:
// JavaScript Document
var cav = document.getElementById("cav").getContext("2d");
function drew() {
//圆形的相关参数
var x = Math.round(Math.random() * 800);//圆形横坐标
var y = Math.round(Math.random() * 600);//圆形纵坐标
var r = Math.round(Math.random() * 40 + 1);//圆形半径
var c = Math.round(Math.random() * 5);//圆形填充颜色
circle(x, y, r, c);//调用绘制圆形的函数
}
function circle(x, y, r, c) {
//用数组存放圆形填充颜色
var style = ['rgba(255,0,0,0.5)', 'rgba(255,255,0,0.5)', 'rgba(255,0,255,0.5)', 'rgba(132,50,247,0.8)', 'rgba(34,236,182,0.5)', 'rgba(147,239,115,0.5)'];
cav.beginPath();
cav.fillStyle = style[c];
cav.arc(x, y, r, 0, Math.PI * 2, true);//绘制圆形
cav.fill();
}html代码:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> </head> <link href="css/style.css" rel="stylesheet" type="text/css"> <body> <div class="mr-cont"> <span>点击图中画布,实现自动绘制随机圆形</span> <canvas height="600" width="800" id="cav" onClick="setInterval(drew,1000)"></canvas> </div> </body> <script src="js/js.js"></script> </html>
css代码:
@charset "utf-8";
/* CSS Document */
.mr-cont {
height: 600px;
width: 800px;
margin: 0 auto;
position: relative;
border: 1px solid #f00;
background: url(../img/bg.png);
}
span {
position: absolute;
top: 50px;
left: 250px;
}js代码解析
让我逐行详细讲解这段 JavaScript 代码:
// JavaScript Document
这是注释行,用来标识这是一个 JavaScript 文档文件。
var cav = document.getElementById("cav").getContext("2d");这行代码获取了 HTML 中 ID 为 "cav" 的 <canvas> 元素,并获取其 2D 渲染上下文。cav 变量现在可以用来在画布上绘制图形。
function drew() {定义了一个名为 drew 的函数,用于生成随机圆形并绘制。
//圆形的相关参数 var x = Math.round(Math.random() * 800);//圆形横坐标
生成随机的圆形横坐标 x,范围在 0 到 800 之间,使用 Math.random() 生成 0 到 1 之间的随机数,乘以 800 后用 Math.round() 四舍五入取整。
var y = Math.round(Math.random() * 600);//圆形纵坐标
生成随机的圆形纵坐标 y,范围在 0 到 600 之间,同样使用 Math.random() 生成随机数并四舍五入。
var r = Math.round(Math.random() * 40 + 1);//圆形半径
生成随机的圆形半径 r,范围在 1 到 41 之间。Math.random() * 40 生成 0 到 40 之间的随机数,加 1 后得到 1 到 41 之间,然后四舍五入取整。
var c = Math.round(Math.random() * 5);//圆形填充颜色
生成随机的颜色索引 c,范围在 0 到 5 之间,用于从颜色数组中选择颜色。
circle(x, y, r, c);//调用绘制圆形的函数}
调用 circle 函数,传入随机生成的圆形参数 x、y、r、c。
function circle(x, y, r, c) {定义了一个名为 circle 的函数,用于绘制圆形。
//用数组存放圆形填充颜色 var style = ['rgba(255,0,0,0.5)', 'rgba(255,255,0,0.5)', 'rgba(255,0,255,0.5)', 'rgba(132,50,247,0.8)', 'rgba(34,236,182,0.5)', 'rgba(147,239,115,0.5)'];
定义一个颜色数组,包含 6 种半透明颜色,每种颜色都使用 RGBA 格式,其中 alpha 值为 0.5 或 0.8,表示透明度。
cav.beginPath();
开始一个新的路径,这是绘制图形前的必要步骤,确保之前的路径不会影响新绘制的图形。
cav.fillStyle = style[c];
设置填充颜色为颜色数组中索引为 c 的颜色。
cav.arc(x, y, r, 0, Math.PI * 2, true);//绘制圆形
使用 arc 方法绘制圆形。参数含义:
x, y:圆心坐标
r:半径
0:起始角度(弧度)
Math.PI * 2:结束角度(完整圆)
true:逆时针方向绘制
cav.fill(); }
填充绘制的圆形。