效果图
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#canvas {
border: 1px solid #eee;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="800"></canvas>
</body>
</html>
<script>
// 文字
let text = '祝大家';
// 文字的尺寸
let fontSize = 150;
// 文字放大的比例
let proportion = 1.5;
// 粒子数组
const particles = [];
// 随机的图片
let imgUrl = ['./images/test.png', './images/22cu612ucen.jpg', './images/25swg975dk1.jpg', './images/oMgEH5ratCnw7cFwzJu71u2IrkRk.jpg'];
class Particle{
constructor(options = {}) {
const { x = 0, y = 0, color = '#f00', image = '' } = options;
this.x = x;
this.y = y;
this.image = image;
}
draw(ctx) {
let image = new Image();
image.crossOrigin = 'anonymous'
image.src = this.image;
image.onload = () => {
ctx.drawImage(image, this.x, this.y, 10, 10);
}
}
}
init();
function init() {
let canvas = document.getElementById('canvas');
let canvasW = canvas.width;
let canvasH = canvas.height;
let ctx = canvas.getContext('2d');
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.font = `${fontSize}px Verdana`;
ctx.fillText(text, 0, 0, 500);
// 获取文字的高度
let textW = ctx.measureText(text).width;
// 获取文字的像素点
let imageData = ctx.getImageData(0,0, textW, fontSize);
// h和w + 8 设置粒子的密集程度
for (let h = 0; h < fontSize; h = h + 8) {
for (let w = 0; w < textW; w = w + 8) {
let opacityIndex = (w + h * textW) * 4 + 3;
if (imageData.data[opacityIndex] > 0) {
particles.push(new Particle({
x: w*proportion,
y: h*proportion,
image: imgUrl[Math.round(Math.random()*3)],
}));
}
}
}
// 设置canvas 原点坐标位置
ctx.translate(0, 300);
for (const particle of particles) {
particle.draw(ctx);
}
}
</script>