·  阅读 9003

1. 没有，你编的
2. 有呀，我认识

先改造一下烟花的源代码

``````//篇幅限制，仅展现部分代码
function createFireworks(x, y) {
var count = 100;
for (var i = 0; i < count; i++) {
var p = {};

p.x = x;
p.y = y;
p.speed = (Math.random() * 5) + .4;
}
}
function drawFireworks(){
for (var i = 0; i < particles.length; i++) {
var p = particles[i];

p.x += vx;
p.y += vy;
p.radius *= 1 - p.speed / 100;
}
}

``````//篇幅限制，仅展现部分代码
function createFireworks(x, y){
var count = 100;
for (var i = 0; i < count; i++) {
var angle = 360 / count * i;

var p = {};
p.x = x;
p.y = y;
p.radians = angle * Math.PI / 180;

}
}
function drawFireworks() {
for (var i = 0; i < particles.length; i++) {
var p = particles[i];

p.x += (p.fx - p.x)/10;
p.y += (p.fy - p.y)/10-(p.alpha-1)*p.speed;
}
}

画布绘制文字

`createFireworks`方法改造如下

``````function createFireworks(x,y,text=""){
if(text!=""){
//绘制文字
}else{
//原有的烟花代码
}
}

``````var fontSize = 120;
var textHeight = fontSize;
context.font=fontSize+"px Verdana";
context.fillStyle = "#ffffff";
context.fillText(text,0,textHeight);

获取点阵数组

``````var imgData = textctx.getImageData(0,0,textWidth,textHeight);

for (var h = 0; h < textHeight; h+=gap) {
for(var w = 0; w < textWidth; w+=gap){
var position = (textWidth * h + w) * 4;
var r = imgData.data[position], g = imgData.data[position + 1], b = imgData.data[position + 2], a = imgData.data[position + 3];
}
}

``````[r,g,b,a,r,g,b,a,r,g,b,a]

``````var fx = x + w - textWidth/2;
var fy = y + h - textHeight/2;

context.fillStyle = "#ffffff";
context.fillRect(fx,fy,1,1);

``````for (var h = 0; h < textHeight; h+=gap) {
for(var w = 0; w < textWidth; w+=gap){
var position = (textWidth * h + w) * 4;
var r = imgData.data[position], g = imgData.data[position + 1], b = imgData.data[position + 2];

if(r+g+b==0)continue;

var p = {};
p.x = x;
p.y = y;
p.fx = x + w - textWidth/2;
p.fy = y + h - textHeight/2;

p.size = Math.floor(Math.random()*2)+1;
p.speed = 1;

setupColors(p);

particles.push(p);
}
}

用它示爱！

``````createFireworks(x, y,["杨幂","我爱你","永远"][Math.floor(Math.random()*3)]);