Canvas

canvas

创建高清的 canvas

1
2
3
4
5
6
7
8
9
10
11
12
const createHDCanvas = (w, h) = >{
const canvas = document.createElement("canvas");
const ratio = window.devicePixelRatio || 1;
canvas.width = w * ratio; // 实际渲染像素
canvas.height = h * ratio; // 实际渲染像素
canvas.style.width = `${w}px`; // 控制显示大小
canvas.style.height = `${h}px`; // 控制显示大小
const ctx = canvas.getContext("2d");
ctx.scale(ratio, ratio);
// canvas 绘制
return canvas;
};

画图 canvas 模糊背景

效果:

GIF 2023-2-20 17-05-28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const blurBg = (div: HTMLDivElement) => {
if (!div) return;
const width = div.offsetWidth;
const height = div.offsetHeight;
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d')!;
// 生成随机的干扰线
for (let i = 0; i < 50; i++) {
ctx.beginPath();
ctx.moveTo(Math.random() * width, Math.random() * height);
ctx.lineTo(Math.random() * width, Math.random() * height);
ctx.strokeStyle = `rgba(${getRandomInt(0, 255)}, ${getRandomInt(0, 255)}, ${getRandomInt(0, 255)}, ${Math.random()})`;
ctx.stroke();
}
// 生成随机的干扰点
for (let i = 0; i < 800; i++) {
ctx.beginPath();
// radius:1
ctx.arc(Math.random() * width, Math.random() * height, Math.random() * 2, 0, 2 * Math.PI);
ctx.fillStyle = `rgba(${getRandomInt(0, 255)}, ${getRandomInt(0, 255)}, ${getRandomInt(0, 255)}, ${Math.random()})`;
ctx.fill();
}
div.style.backgroundImage = `url(${canvas.toDataURL('image/png', 0.8)})`;
};