<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
html, body {
margin: 0;
padding: 0;
}
</style>
<script>
let ctx
const COLOR = "#000";
const FONT_SIZE = 15
const points = []
const PARTICLES_SIZE = 2 // 粒子大小
let canvas
function Point(x, y, r, g, b, a) {
const TEXT_CONTENT = canvas.textContent; // canvas里面文字的内容
const text_width = ctx.measureText(TEXT_CONTENT).width
this.x = x * 4
this.y = y * 4
this.r = r
this.g = g
this.b = b
this.a = a
this.getX = function () {
return this.x;
}
this.getY = function () {
return this.y;
}
}
const adjustText = () => {
const TEXT_CONTENT = canvas.textContent; // canvas里面文字的内容
ctx.fillStyle = COLOR;
ctx.textAlign = "center"
ctx.font = `${FONT_SIZE}px serif`
ctx.fillText(TEXT_CONTENT, canvas.width / 2, canvas.height / 2);
const text_width = ctx.measureText(TEXT_CONTENT).width
const image_data = ctx.getImageData(canvas.width / 2 - text_width / 2, canvas.height / 2 - FONT_SIZE, text_width, FONT_SIZE);
// 遍历当前canvas的宽和高,然后每个需要粒子的坐标记录下来
for (let index in image_data.data) {
/*
遍历data里面的数据,找出不是0的坐标系,
0 1 2 3
4 5 6 7
8 9 10 11
y轴 x轴 对应的值
0 0 0
0 0 1
0 0 2
0 0 3
1 0 4
1 0 5
1 0 6
公式为:y轴*x轴的长度 + x轴,就是我们对应的
现在我们知道了他所在的下标,和x轴的宽度,所以现在X和Y轴的公式为
0 1 2 3 4
5 6 7 8 9
下标 x轴的长度 对应的值轴 x轴
0 5 0 0
0 5 1 0
0 5 2 0
0 5 3 0
0 5 4 0
1 5 5 1
1 5 6 1
1 5 7 1
1 5 8 1
现在获取9对应的x轴和y轴
x轴坐标的公式为
下标 % X轴的长度
y轴坐标的公式为
(下标 - x) / x轴的长度
*/
if (image_data.data[index] !== 0) {
// 这里除以四是因为image.data里面的值放的是rgba,每四位数代表一个坐标
const num = Math.floor(index / 4);
const x = num % image_data.width;
const y = Math.floor((num - x) / image_data.width)
points.push(new Point(x, y, image_data.data[index], image_data.data[index + 1], image_data.data[index + 2], image_data.data[index + 2]))
}
}
}
window.onload = () => {
canvas = document.getElementById("particle");
ctx = canvas.getContext('2d', {alpha: true,});
init()
}
const draw = () => {
/*
清除画布上的东西,
开始遍历之前放置的粒子,然后绘制粒子,最后填充颜色
*/
ctx.clearRect(0, 0, canvas.width, canvas.height);
let point;
for (let i = 0; i < points.length; i++) {
point = points[i];
ctx.fillStyle = "rgba(" + point.r + "," + point.g + "," + point.b + "," + point.a + ")";
ctx.beginPath();
ctx.arc(point.getX(), point.getY(), PARTICLES_SIZE, 0, 2 * Math.PI, true);
ctx.fill();
}
}
const init = () => {
// resizeCanvas()
adjustText()
draw()
}
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight - 4;
}
</script>
</head>
<body>
<!-- 绘制canvas -->
<canvas id="particle" width="400" height="500">hello world</canvas>
</body>
</html>
通过粒子绘制文字
最新推荐文章于 2024-08-15 18:19:19 发布