使用getImageData接口获取图片的像素点,然后基于像素点实现动画效果,封装成一个简单的lib

particle image

ParticleImage.js

/*

The MIT License (MIT)

Copyright (c) 2015 arest

Permission is hereby granted, free of charge, to any person obtaining a copy of

this software and associated documentation files (the "Software"), to deal in

the Software without restriction, including without limitation the rights to

use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of

the Software, and to permit persons to whom the Software is furnished to do so,

subject to the following conditions:

The above copyright notice and this permission notice shall be included in all

copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR

IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS

FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR

COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER

IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN

CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

/**

* Add particle animation for image

* usage:

// in html file

// you can set default background image as usual

#logo {

margin-left:20px;

margin-top:20px;

width:160px;

height:48px;

background:url('logo_s2.png');

}

*

* @author tianx.qin (rushi_wowen@163.com)

* @file ParticleImage.js

* @version 0.9

*/

var ParticleImage = (function(window) {

var container = null, canvas = null;

var ctx = null, _spirit = [], timer = null,

cw = 0, ch = 0, // container width/height

iw = 0, ih = 0, // image width/height

mx = 0, my = 0, // mouse position

bMove = true,

MOVE_SPAN = 4, DEFAULT_ALPHA = 100,

speed = 100, S = {"fast":10, "mid":100, "low":300},

ALPHA = 255 * 255;

// spirit class

var Spirit = function(data) {

this.orginal = {

pos: data.pos,

x : data.x, y : data.y,

r : data.r, g : data.g, b : data.b, a : data.a

};

// change state, for animation

this.current = {

x : data.x,

y : data.y,

a : data.a

};

};

/**

* move spirit to original position

*/

Spirit.prototype.move = function() {

var cur = this.current, orig = this.orginal;

if ((cur.x === orig.x) && (cur.y === orig.y)) {

//console.log("don't move:" + cur.y);

return false;

}

//console.log("move:" + cur.y);

var rand = 1 + Math.round(MOVE_SPAN * Math.random());

var offsetX = cur.x - orig.x,

offsetY = cur.y - orig.y;

var rad = offsetX == 0 ? 0 : offsetY / offsetX;

var xSpan = cur.x < orig.x ? rand : cur.x > orig.x ? -rand : 0;

cur.x += xSpan;

var tempY = xSpan == 0 ? Math.abs(rand) : Math.abs(Math.round(rad * xSpan));

var ySpan = offsetY < 0 ? tempY : offsetY > 0 ? -tempY : 0;

cur.y += ySpan;

cur.a = ((cur.x === orig.x) && (cur.y === orig.y)) ? orig.a : DEFAULT_ALPHA;

return true;

};

/**

* set random position

*/

Spirit.prototype.random = function(width, height) {

var cur = this.current;

cur.x = width + Math.round(width * 2 * Math.random());

this.current.y = height + Math.round(height * 2 * Math.random());

};

/**

* set random positions for all spirits

*/

var _disorder = function() {

var len = _spirit.length;

for (var i = 0; i < len; i++) {

_spirit[i].random(cw, ch);

}

};

/**

* start to move spirit

*/

var _move = function() {

var sprt = _spirit;

var len = sprt.length;

var isMove = false; // whether need to move

for (var i = 0; i < len; i++) {

if (sprt[i].move()) {

isMove = true;

}

}

isMove ? _redraw() : _stopTimer();

};

/**

* redraw all spirits while animating

*/

var _redraw = function() {

var imgDataObj = ctx.createImageData(iw, ih);

var imgData = imgDataObj.data;

var sprt = _spirit;

var len = sprt.length;

//console.log("redraw image : " + len);

for (var i = 0; i < len; i++) {

var temp = sprt[i];

//console.log("item : " + JSON.stringify(temp));

var orig = temp.orginal;

var cur = temp.current;

var pos = (cur.y * iw + cur.x) * 4;

imgData[pos] = orig.r;

imgData[pos + 1] = orig.g;

imgData[pos + 2] = orig.b;

imgData[pos + 3] = cur.a;

}

ctx.putImageData(imgDataObj, 0, 0);

};

/**

* add mousemove/mouseclick event

*/

var _addMouseEvent = function(c) {

c.addEventListener("mouseenter", function(e) {

//console.log("e.y:" + e.clientY + ", " + container.offsetTop);

_startTimer();

});

c.addEventListener("click", function() {

// disorder all spirits and start animation

_startTimer();

});

};

/**

* calculate all pixels of the logo image

*/

var _checkImage = function(imgUrl, callback) {

// var tempCanvas = document.getElementById("temp");

//canvas.width = width;

//canvas.height = height;

var proc = function(image) {

var w = image.width, h = image.height;

iw = w, ih = h;

//console.log("proc image " + image + "," + w + "," + h);

canvas = _createCanvas();

// hide container background

container.style.backgroundPosition = (-w) + "px";

container.style.backgroundRepeat = "no-repeat";

ctx.drawImage(image, 0, 0);

// this may cause security error for CORS issue

try {

var imgData = ctx.getImageData(0, 0, w, h);

var arrData = imgData.data;

for (var i = 0; i < arrData.length; i += 4) {

var r = arrData[i], g = arrData[i + 1], b = arrData[i + 2], a = arrData[i + 3];

if (r > 0 || g > 0 || b > 0 || a > 0) {

var pos = i / 4;

_spirit.push(new Spirit({

x : pos % w, y : Math.floor(pos / w),

r : r, g : g, b : b, a : a

}));

}

}

return true;

} catch (e) {

// do nothing

return false;

}

//return out;

};

var img = new Image();

img.src = imgUrl;

if (img.complete || img.complete === undefined) {

proc(img) && callback && callback();

} else {

img.onload = function() {

proc(img) && callback && callback();

};

}

};

// use "requestAnimationFrame" to create a timer, need browser support

var _timer = function(func, dur) {

//console.log("speed is " + dur);

var timeLast = null;

var bStop = false;

var bRunning = false; // prevent running more than once

var _start = function() {

if (func) {

if (! timeLast) {

timeLast = Date.now();

func();

} else {

var current = Date.now();

if (current - timeLast >= dur) {

timeLast = current;

func();

}

}

}

if (bStop) {

return;

}

requestAnimationFrame(_start);

};

var _stop = function() {

bStop = true;

};

return {

start : function() {

if (bRunning) {

//console.log("already running..");

return;

}

//console.log("start running..");

bRunning = true;

bStop = false;

_disorder();

_start();

},

stop : function() {

_stop();

bRunning = false;

}

};

};

var _startTimer = function() {

if (! timer) {

timer = _timer(function() {

bMove && _move();

}, speed);

}

timer.start();

};

var _stopTimer = function() {

timer && timer.stop();

};

/**

* start process

*/

var _create = function(imgUrl) {

_checkImage(imgUrl, function() {

//_createSpirits();

_addMouseEvent(canvas);

//_startTimer();

});

};

var _setSpeed = function(s) {

S[s] && (speed = S[s]);

};

/**

* check whether browser supports canvas

*/

var _support = function() {

try {

document.createElement("canvas").getContext("2d");

return true;

} catch (e) {

return false;

}

};

/**

* create a canvas element

*/

var _createCanvas = function() {

var cav = document.createElement("canvas");

cav.width = iw;

cav.height = ih;

container.appendChild(cav);

ctx = cav.getContext("2d");

return cav;

};

/**

* initialize container params

*/

var _init = function(c, s) {

if ((! c) || (! _support())) { // DIV id doesn't exist

return false;

}

container = c;

cw = c.clientWidth;

ch = c.clientHeight;

s && _setSpeed(s);

return true;

};

/**

* export

*/

return {

"create" : function(cId, imgUrl, s) { // user can set move speed by 's'['fast','mid','low']

_init(document.getElementById(cId), s) && _create(imgUrl);

}

};

})(window);

以上所述就是本文的全部内容了,希望大家能够喜欢。

声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理

html粒子特效图片切换,javascript转换静态图片,增加粒子动画效果_javascript技巧...相关推荐

  1. 如何用js实现点击图片切换为另一图片,再次点击恢复到原图片

    如何用js实现点击图片切换为另一图片,再次点击恢复到原图片 <!DOCTYPE html> <html lang="en"> <head>< ...

  2. jquery实现点击图片切换为另一图片,再次点击恢复到原图片

    在项目里,有时候会写这样的开关效果,点击开关来回切换,也就是jquery实现点击图片切换为另一图片,再次点击恢复到原图片. 下面是一个小的demo示例: <!DOCTYPE html> & ...

  3. html实现简单图片切换,JavaScript实现简单的图片切换

    JavaScript实现图片切换,主要用到setInterval()函数和clearInterval()函数,前者功能是开启动画,后者功能则为清除动画(可理解为使动画停止),为了使动画停止,则需要定义 ...

  4. iOS粒子特效、仿微信朋友圈、转场动画、抢红包动画等源码

    iOS精选源码 viewController 之间的转场动画 swift版 视频添加水印及粒子特效 小红点(消息推送提醒)完整解决方案 仿微信朋友圈–CircleOfFriendsDisplay 图片 ...

  5. vue 直接访问静态图片_vue中本地静态图片路径写法

    这篇文章给大家介绍了vue中本地静态图片路径写法及Vue.js中引用图片路径的方式,需要的朋友参考下吧 这里写图片描述 需求:如何components里面的index.vue怎样能把assets里面的 ...

  6. java pdf输出图片_Java PDF转换成图片并输出给前台展示

    首先需要导入所需工具类 org.apache.pdfbox fontbox 2.0.1 org.apache.pdfbox pdfbox 2.0.1 cn.hutool hutool-all 4.1. ...

  7. html设置图片切割,JavaScript html js图片切割系统

    JavaScript html js图片切割系统,裁剪,图片处理 关键字: javascript html js 图片切割系统裁剪处理 图片切割(裁剪),这里需要声明一下: 首先js是不能操作客户端文 ...

  8. php把buffer转化为图片_php base64转换成图片的方法

    php base64转换成图片的方法:首先获取到前端传递的值:然后设置文件路径和命名文件名称:接着将数据流文件写入创建的文件内容中:最后将路径信息返回给前端使用即可. 将base64数据流文件转换为图 ...

  9. php js特效代码如何用,phpstorm编写代码增加代码爆炸效果

    Awesome Power Mode 下载地址:https://github.com/codeinthedark/awesome-power-mode A curated list of power ...

  10. html数字动画效果,原生JavaScript代码实现数字更新的动画效果

    前言 在很多数据统计类型网站的首页,经常会看到数据在动态的更新,而且会以动画的效果呈现. 今天这篇文章我们就来看看这个效果如何实现吧. 文中的代码已经放到github上了,感兴趣的同学可以自取.htt ...

最新文章

  1. 使用PHP+Sphinx建立高效的站内搜索引擎
  2. 白盒测试之路径测试练习
  3. iOS UITapGestureRecognizer手势和UIButton 以及UITabelView点击事件冲突
  4. java闭合数据_java多线程中线程封闭详解
  5. SQLite入门与分析(二)---设计与概念
  6. The property delegate of CALayer cause Crash.
  7. superset出现A valid API access token is required to use Mapbox data
  8. [转]cocos2d游戏开发,常用工具集合
  9. java 后台和前端的消息提醒_滴滴Java后台3面题目:网络+内存溢出+各种锁+高性能+消息队列...
  10. OpenJudge NOI 1.8 24:蛇形填充数组
  11. U盘文件系统类型 和 linux 挂载 和 卸载
  12. 德芙背后刻骨铭心的痛
  13. vissim免修改时间工具_视频剪辑工具premiere最基础使用教程
  14. win10系统,使用Windows照片查看器打开图片
  15. wps office应用计算机等级考试,全国计算机等级考试一级教程:计算机基础及WPS Office应用(2016年版)...
  16. 【7gyy】支招:自检性能搞定网速慢电脑卡的问题
  17. 服务器和交换机物理连接_什么是路由器交换机?路由器交换机说明!
  18. mini计算机结构,通用解决方案:[教程信息]计算机主板ATX / Micro ATX / Mini-ITX的几种结构标准...
  19. TOP100summit 2017:小米唐沐等大咖精心挑选的100个年度研发案例实践
  20. 【超详细】SpringBoot与Shiro整合-权限管理实战实操(附源码地址)

热门文章

  1. Linux(七,八)SHELL解释器、用户和用户组管理详解
  2. 模电笔记3 三极管 光电三极管
  3. 微型计算机硬件系统包括什么,微型计算机硬件系统由什么组成(6个基本组成部件)...
  4. 从鼠标点击位置发射射线检测是否点击到3D世界中的物体
  5. Python实现太极图案
  6. mac去除视频水印用什么软件?
  7. win7计算机系统更新,win7电脑版本低怎么升级?win7电脑版本低的解决方法
  8. 使用iperf测试网速
  9. 图形界面中消息盒子的使用
  10. YTU OJ 2476 C++习题 继承与组合