JavaScript transforms static picture, increases particle animation effect _javascript skill

Source: Internet
Author: User
Tags abs rand

Use the Getimagedata interface to get the pixel point of the picture, then animate it based on the pixel, and encapsulate it into a simple lib

<! DOCTYPE html>
 
 

Particleimage.js

/* The MIT License (MIT) Copyright (c) 2015 Arest Permission is hereby granted, free of charge ng a copy of this software and associated documentation files (the ' software '), to deal in the software without n, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Copie
 
S of the Software, and to permit persons to whom the Software are furnished to does, subject to the following: The above copyright notice and this permission notice shall is included in all copies or substantial portions of the Sof
 
Tware. The SOFTWARE is provided ' as is ', without WARRANTY of any KIND, EXPRESS OR implied, including BUT not LIMITED to the Warra Nties of merchantability, FITNESS for A particular purpose and noninfringement. In NO EVENT SHALL the AUTHORS or COPYRIGHT holders is liable for all CLAIM, damages or other liability, WHETHER in a acti On CONTRACT, TORT OR Otherwise, arising from, out of OR in CONNECTION with the SOFTWARE or the "dealings" in the SOFTWARE. * */** * ADD particle animation for image * Usage: <script type= "Text/javascript" src= "Particleimage.js" >&lt  ;/script> <script> window.onload = function () {//is sure to use image file in your own server
        (Prevent CORS issue)
      Particleimage.create ("logo", "Logo_s2.png", "fast");
    }; </script>//In HTML file <div id= "logos" ></div>//You can set default background image as U
      Sual #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 = (functio
  N (window) {var container = null, canvas = NULL; var ctx = null, _spirit = [], timer = NULL, CW = 0, ch = 0,//container width/height IW = 0, ih = 0,//Image wid Th/height mx = 0, my = 0,//mouse position bmove = true, Move_span = 4, Default_alpha = +, speed = m, S = {"Fast": 10, "
 
  Mid ":", "low": 255, ALPHA = 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", Fu
      Nction (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 Tempcanv
    as = 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 could 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 no 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 the "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 &&amP
  Timer.stop ();
 
  }; /** * START process/var _create = function (Imgurl) {_checkimage (Imgurl, function () {//_createspirit
      S ();
      _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 * * "create": function (CId, Imgurl, s) {//user can set move speed by ' s ' [' Fast ', ' mid ',
    ' Low '] _init (document.getElementById (cId), s) && _create (Imgurl);
}
  };
 }) (window);

The above is the entire contents of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.