HTML5标签--Canvas实际应用:
1:绘制直线
2:绘制五角星
3:动态矩形(随机函数很重要)
4:动态弧线
必备代码:
// 1:获取canvas标签
var canvas = document.querySelector("canvas");
// 2:获取canvas的上下文环境
var ctx = canvas.getContext("2d");//画笔,配置工具
给个宽高
在body里写:<canvas width= "500" height= '500'></canvas>
或 script中定义
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
//写完window的宽度,高度
var sw = window.innerWidth;
var sh = window.innerHeight;
1:绘制直线
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(100,100);
ctx.closePath();
ctx.strokeStyle="gold";
ctx.stroke();//描边绘制
2:绘制五角星
let drawStart = () => {
ctx.beginPath();
ctx.moveTo(50, 100);
ctx.lineTo(250, 100);
ctx.lineTo(100, 200);
ctx.lineTo(150, 25);
ctx.lineTo(200, 200);
ctx.closePath();
//描边
// ctx.strokeStyle="gold";
// ctx.stroke();//描边绘制
ctx.lineWidth = '8';
ctx.strokeStyle = "tomato";
ctx.stroke();
// 顺序很关键,会覆盖
//填充
ctx.fillStyle = "gold";
ctx.fill();
}
如果填充在前面,画线在后面
(
ctx.fillStyle = "gold";
ctx.fill();
ctx.strokeStyle = "tomato";
ctx.stroke();
)
3:动态矩形
//绘制矩形
let drawRect = () => {
//随机宽高
let w = rand(50, 200);
let h = rand(50, 200);
let x = rand(0, window.innerWidth - w);
let y = rand(0, window.innerHeight - h);
ctx.beginPath();
ctx.strokeStyle = randColor();
ctx.strokeRect(x, y, w, h);
ctx.stroke();
ctx.fillStyle = randColor();
ctx.fill();
}
随机函数(随机颜色,随机大小)
let rand = (min, max) => Math.round(Math.random() * (max - min) + min);//随机函数
let randColor = () => `rgb(${rand(0, 255)},${rand(0, 255)},${rand(0, 255)})`;
setInterval(() => {
//清空画布
ctx.clearRect(0, 0, window.innerWidth, innerHeight);
for (let i = 0; i < 50; i++) {
drawRect();
}
}, 2000)
动态矩形let和script实现
4:动态弧线
//绘制 弧线
let drawHu = () => {
//半径
var r = rand(30, 120);
//中心点
let x = rand(r, sw - r);
let y = rand(r, sh - r);
//起始角度,结束角度
let sa = rand(0, 360) / 360 * Math.PI * 2;
let ea = rand(0, 360) / 360 * Math.PI * 2;
let is = Math.random() > 0.5 ? true : false;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.arc(x, y, r, sa, ea, is);
ctx.closePath();
ctx.strokeStyle = randColor();
ctx.stroke();
ctx.fillStyle = randColor();
ctx.fill();
}
随机函数中把
drawRect();
改成
drawHu();
就可以执行了