javascript转换静态图片,增加粒子动画效果

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

rush:xhtml;"> particle image
logo">

ParticleImage.js

rush: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:
    <script type="text/javascript" src="ParticleImage.js"> // in html file
    logo">
    // 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,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);
    };

/**

  • 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);
  // this may cause s<a href="https://www.jb51.cc/tag/ecurity/" target="_blank" class="keywords">ecurity</a> error for CORS issue
  try {
    var imgData = ctx.ge<a href="https://www.jb51.cc/tag/timage/" target="_blank" class="keywords">timage</a>Data(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 <a href="https://www.jb51.cc/tag/nothing/" target="_blank" class="keywords">nothing</a>
    return false;
  }
  //return out;
};

var img = new Image();
img.src = <a href="https://www.jb51.cc/tag/imgur/" target="_blank" class="keywords">imgur</a>l;
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;
    _<a href="https://www.jb51.cc/tag/dis/" target="_blank" class="keywords">dis</a>order();
    _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);

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


什么是深拷贝与浅拷贝?深拷贝与浅拷贝是js中处理对象或数据复制操作的两种方式。‌在聊深浅拷贝之前咱得了解一下js中的两种数据类型:
前言 今天复习了一些前端算法题,写到一两道比较有意思的题:重建二叉树、反向输出链表每个节点 题目 重建二叉树: 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列 {1,2,4,7,3,5,6,8} 和中序遍历序列 {
最近在看回JavaScript的面试题,this 指向问题是入坑前端必须了解的知识点,现在迎来了ES6+的时代,因为箭头函数的出现,所以感觉有必要对 this 问题梳理一下,所以刚好总结一下JavaScript中this指向的问题。
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小
JS怎么获取当前时间戳
JS如何判断对象是否为数组
JS怎么获取图片当前宽高
JS对象如何转为json格式字符串
JS怎么获取图片原始宽高
怎么在click事件中调用多个js函数
js如何往数组中添加新元素
js如何拆分字符串
JS怎么对数组内元素进行求和
JS如何判断屏幕大小
js怎么解析json数据
js如何实时获取浏览器窗口大小
原生JS实现别踩白块小游戏(五)