最终图

 

首先

const canvas = document.getElementById('app');
const ctx = canvas.getContext('2d');
canvas.width = document.documentElement.clientWidth;//或者window.innerWidth、window.innerHeight
canvas.height = document.documentElement.clientHeight;

将背景设置颜色进行线性渐变

const grad = ctx.createLinearGradient(0,0,0,canvas.height);
grad.addColorStop(0, '#000');
grad.addColorStop(1, 'blue');
ctx.fillStyle = grad;
ctx.fillRect(0, 0, canvas.width, canvas.height);

接下来进行循环画星星

for(let i = 0; i < 200; i++){
let r = Math.random() * 5 + 5;//星星外圆的半径范围是0-5
let x = Math.random() * canvas.width;//星星位置的横轴偏移量
let y = Math.random() * canvas.height * 0.65;//星星位置的竖轴偏移量,在整个canvas高度的65%
let a = Math.random() * 360;//为旋转的角度 0-360
drawStar(ctx, x, y, r, a);//画星星的函数
}

对星星进行分析,可得到

分别由两个圆,定五角星的10个点,再依次取点进行连线绘制即可

function drawStar(ctx, x, y, R, rot){//小圆半径为大圆的一半
ctx.beginPath();
for(let i = 0; i < 5; i++) {//循环5次,每次取2个点,总共取10个点
ctx.lineTo(Math.cos((18 + i * 72 - rot) / 180 * Math.PI) * R + x, -Math.sin((18 + i * 72 - rot) / 180 * Math.PI) * R + y);
ctx.lineTo(Math.cos((54 + i * 72 - rot) / 180 * Math.PI) * R * 0.5 + x, -Math.sin((54 + i * 72 - rot) / 180 * Math.PI) * R * 0.5 + y)
}
ctx.closePath();
ctx.fillStyle = '#fff';
ctx.lineWidth = 1;

ctx.fill();
ctx.stroke();
}