HTML部分
<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
</head>
<body>
<img id="imgPath" src="img_proxy.php?i=http%3A%2F%2Fprofile.ak.fbcdn.net%2Fhprofile-ak-snc4%2F49062_1041673900_6306_n.jpg">
<script src="particle.js"></script>
</body>
</html>
JS部分
//圖片位置
$('#imgPath').hide();
var img_path = $('#imgPath').attr('src');
//canvas dom
$('body').append(
$('<div id="main"/>').append(
$('<canvas id="canvas"/>').attr(
{width:$(window).width(),height:$(window).height()}
)
)
);
參數宣告
var tmpImg = new Array();
var tmpPosTop = new Array();
var tmpPosLeft = new Array();
var aGoTop = new Array();
var aGoLeft = new Array();
var Flag = new Array();
var screenTop;
var screenLeft;
var pHeight;
var pWidth;
var imgTop;
var imgLeft;
var i = 0;
canvas處理
//抓下圖片貼到canvas
var canvasDom = $('#canvas').get(0);
var ctx = canvasDom.getContext('2d');
ctx.fillStyle= 'FFFFFF';
var img = new Image();
img.src = img_path;
img.onload = function(){
screenTop = Math.floor(($(window).height())/2) - this.height;
screenLeft = Math.floor(($(window).width())/2) - this.width;
pHeight = Math.floor(this.height/15);
pWidth = Math.floor(this.width/15);
imgTop = screenTop;
imgLeft = screenLeft;
ctx.drawImage(img,imgLeft,imgTop);
//把圖存到array裡
while( imgTop < this.height+screenTop && imgLeft < this.width+screenLeft ){
tmpImg[i] = ctx.getImageData(imgLeft,imgTop,pWidth,pHeight);
tmpPosTop[i] = imgTop;
tmpPosLeft[i] = imgLeft;
i++;
imgLeft += pWidth;
if( imgTop < this.height+screenTop && imgLeft >= this.width+screenLeft ){
imgLeft = 0;
imgTop += pHeight;
}
}
var pImg = new Array();
i = 0;
//計算要到達的目的座標
while(i < tmpImg.length){
if( pImg[i] != 1 ){
pImg[i] = 1;
var randLeft = Math.floor(Math.random()*(img.width));
var randTop = Math.floor(Math.random()*(img.height));
var randDir = Math.floor(Math.random()*10);
if( randDir % 4 == 1 ){
randLeft = randLeft * -1;
randTop = randTop * -1;
}else if(randDir % 4 == 2){
randTop = randTop * -1;
}else if(randDir % 4 == 3){
randLeft = randLeft * -1;
}
var goLeft = tmpPosLeft[i] + randLeft;
var goTop = tmpPosTop[i] + randTop;
if( goLeft < 0 ){
goLeft = 0;
}
if( goTop < 0 ){
goTop = 0;
}
if( goLeft >= $(window).width() ){
goLeft = $(window).width();
}
if( goTop >= $(window).height() ){
goTop = $(window).height();
}
aGoTop[i] = goTop;
aGoLeft[i] = goLeft;
i++;
}
}
i = 0;
while( i < tmpImg.length ){
//移動圖片區塊
Flag[i] = setInterval('moveParticle('+i+');',1);
i++;
}
}
移動圖塊var moveParticle = function (i){
if( Math.abs(tmpPosLeft[i] - aGoLeft[i]) < 5 || Math.abs(tmpPosTop[i] - aGoTop[i]) < 5 ){
clearInterval(Flag[i]);
}
ctx.fillRect(tmpPosLeft[i],tmpPosTop[i],pWidth,pHeight);
if( aGoLeft[i] > tmpPosLeft[i] ){
tmpPosLeft[i]++;
}else{
tmpPosLeft[i]--;
}
if( aGoTop[i] > tmpPosTop[i] ){
tmpPosTop[i]++;
}else{
tmpPosTop[i]--;
}
ctx.putImageData(tmpImg[i],tmpPosLeft[i],tmpPosTop[i]);
}
實作範例: http://excite.978.tw/html5/particle.php
沒有留言:
張貼留言