码迷,mamicode.com
首页 > 其他好文 > 详细

canvas 粒子效果

时间:2017-10-07 17:43:42      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:java   网页   log   block   nbsp   ati   show   anim   animation   

var canvas = document.createElement(‘canvas‘);

  var cxt = canvas.getContext(‘2d‘);
  var W = canvas.width = 500;
  var H = canvas.height = 200;
  var str = ‘Grewer,点击此处‘;
  cxt.textBaseline = ‘top‘;
  cxt.font = ‘60px  宋体‘
  var sw = cxt.measureText(str).width;
  if(sw > W){
      sw = W;
  }
  cxt.fillText(str,(W - sw)/2,(H - 60)/2,W);

  canvas.style.border = ‘1px solid #ddd‘

  document.body.appendChild(canvas);

  var imageData = cxt.getImageData(0,0,W,H); 


  var getV = function(){
  	var v = (Math.random()*4-2);
  	if((-0.1<=v && v<=0)||(0<v&& v<0.1)){
  		v = getV();
  	}
  	return v;
  }

  function getDots(imageData){
    //从imageData对象中取得粒子,并存储到dots数组中
    var dots = [];
    //dots的索引
    var index = 0;
    for(var i = 0; i < W; i++){
      for(var j = 0; j < H ;j++){
        //data值中的红色值
        var k = 4*(i + j*W);
        //data值中的透明度
        if(imageData.data[k+3] > 0){
          dots[index++] = {
            ‘index‘:index,
            ‘x‘:i,
            ‘y‘:j,
            ‘red‘:k,
            ‘vX‘:getV(),
            ‘vY‘:getV(),
          }
         
        }
      }
    }   
    var newDots = [];
    var len = dots.length;
    for(var i = 0; i < len; i++){
      newDots.push(dots.splice(Math.floor(Math.random()*dots.length),1)[0]);
    }
    return newDots;

  }

var dataArr = getDots(imageData)


var random  = function(){
  	cxt.clearRect(0,0,W,H);
  	
  	for(var i = 0; i < dataArr.length; i++){
        var temp = dataArr[i];
        temp.x += temp.vX;
        temp.y += temp.vY
        cxt.fillRect(temp.x,temp.y,1,1);             
      }

    window.requestAnimationFrame(random);  
  }
document.onclick = function(e){
	 e = e || event;
    var x = e.clientX - canvas.getBoundingClientRect().left;
    var y = e.clientY - canvas.getBoundingClientRect().top;

    if((0<=x)&&(x<=500)&&(0<=y)&&(y<=200)){
    	random();
    }
}

  

 参考文章:http://www.cnblogs.com/xiaohuochai/p/7452898.html

 网页查看: http://en.jsrun.net/JfiKp/show

 

canvas 粒子效果

标签:java   网页   log   block   nbsp   ati   show   anim   animation   

原文地址:http://www.cnblogs.com/Grewer/p/7635060.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!