canvas中普通动效与粒子动效的实现代码示例

2020-04-25 07:57:58易采站长站整理

imageData=ctx.getImageData((canvas.width-image.width)/2,(canvas.height-image.height)/2,image.width,image.height); //获取图表像素信息
//绘制图像
};

像素信息

图片的大小为300*300,共有90000个像素,每个像素占4位,存放rgba数据。

粒子绘制


function getPixels(){
var pos=0;
var data=imageData.data; //RGBA的一维数组数据
//源图像的高度和宽度为300px
for(var i=1;i<=image.width;i++){
for(var j=1;j<=image.height;j++){
pos=[(i-1)*image.width+(j-1)]*4; //取得像素位置
if(data[pos]>=0){
var pixel={
x:(canvas.width-image.width)/2+j+Math.random()*20, //重新设置每个像素的位置信息
y:(canvas.height-image.height)/2+i+Math.random()*20, //重新设置每个像素的位置信息
fillStyle:'rgba('+data[pos]+','+(data[pos+1])+','+(data[pos+2])+','+(data[pos+3])+')'
}
pixels.push(pixel);
}
}
}
}
function drawPixels() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0,0,canvas.width,canvas.height);
var len = pixels.length, curr_pixel = null;
for (var i = 0; i < len; i++) {
curr_pixel = pixels[i];
ctx.fillStyle = curr_pixel.fillStyle;
ctx.fillRect(curr_pixel.x, curr_pixel.y, 1, 1);
}
}

粒子时钟

渲染文字时钟


function time() {
ctx.clearRect(0,0,canvas.width,canvas.height)
ctx.font = "150px 黑体";
ctx.textBaseline='top';
ctx.fillStyle = "rgba(245,245,245,0.2)";
ctx.fillText(new Date().format('hh:mm:ss'),(canvas.width-textWidth)/2,(canvas.height-textHeight)/2,textWidth,textHeight);
}

效果

获取粒子

文字转换粒子概念同上,获取选定区域的像素,根据筛选条件进行选择并存入数组。经过遍历后重新绘制。


function getPixels(){
let imgData = ctx.getImageData((canvas.width-textWidth)/2,(canvas.height-textHeight)/2,textWidth,textHeight);
let data = imgData.data
pixelsArr = []for(let i=1;i<=textHeight;i++){
for(let j=1;j<=textWidth;j++){
pos=[(i-1)*textWidth+(j-1)]*4; //取得像素位置
if(data[pos]>=0){
var pixel={
x:j+Math.random()*20, //重新设置每个像素的位置信息
y:i+Math.random()*20, //重新设置每个像素的位置信息
fillStyle:'rgba('+data[pos]+','+(data[pos+1])+','+(data[pos+2])+','+(data[pos+3])+')'
};
pixelsArr.push(pixel);
}
}
}
}

imgData