於是試著把facebook上朋友的照片取下來後組合成蒙太奇效果個人圖
實作範例教學:
Part I. php code 取得facebook權限並抓取朋友的個人照
$facebook = new Facebook(array(
'appId' => $facebook_app_key,
'secret' => $facebook_app_secret,
'cookie' => true
));
if( !$facebook->getSession() ){
$auth_url = $facebook->getLoginUrl();
header('Location: '.$auth_url);
exit;
}else{
$fb_id = $facebook->getUser();
try{
$aUserData = $facebook->api(array(
'method' => 'fql.query',
'query' => 'select pic_square from user where uid='.$fb_id
));
$UserImg = $aUserData[0]['pic_square'];
}catch(Exception $e){ }
try{ //抓取朋友的圖片
$aFriend = $facebook->api(array(
'method' => 'fql.query',
'query' => 'select uid,pic_square from user where uid in (select uid1 from friend where uid2 = '.$fb_id.') limit 360',
));
shuffle($aFriend);
}catch(Exception $e){ }
}
Part II. HTML部份
CSS
<style>
#friend ul li {list-style-type:none;}
#friend .friendimg{position:absolute;width:10px;top:-1000px;}
#me {position:absolute;top:0px;left:0px;z-index:1;}
#me ul li {list-style-type:none;}
#me .meimg {width:600px;height:600px;position:absolute;top:-1000px;}
#msg {color:#0000FF;}
</style>
BODY
<p>如圖片顯示不正常,重新整理一次即可</p>
<p><span id="msg">正在抓取朋友個人照...請等待</span></p>
<canvas id="img_canvas" width="600" height="600"></canvas><!-- 顯示結果的canvas -->
<canvas id="canvas_me" width="600" height="600"></canvas><!-- 半透明個人用 -->
<div id="me"> <!-- 自己的圖片 -->
<ul>
<li><img class="meimg" src="<?php echo htmlspecialchars($UserImg); ?>"></li>
</ul>
</div>
<div id="friend"> <!-- 朋友的圖片 -->
<ul>
<?php foreach( $aFriend as $k => $v ){
echo '<li><img class="friendimg" src="'.htmlspecialchars($v['pic_square']).'"></li>'."\n";
}
?>
</ul>
</div>
Part III. Javascript部分
$(window).load(function() { //全部的圖載完才開始跑
var canvas = $("#img_canvas").get(0);
if( typeof canvas.getContext == 'undefined' ){
$('#msg').html('組圖失敗,原因:瀏覽器不支援HTML5');
return;
}
//將朋友圖加到canvas裡
var ctx = canvas.getContext("2d");
var img_top = 0;
var img_left = 0;
var total = 3600;
var max = $('#friend .friendimg').length;
var i=0;
while( i<total ){
var seed = Math.floor(Math.random()*max);
var img = new Image();
var img_tmp = $('#friend .friendimg');
var img_tmp_dom = img_tmp[seed];
img.src = img_tmp_dom.src;
if( img.src.length > 3 && img_tmp_dom.complete == true){
ctx.drawImage(img, img_top,img_left,10,10);
img_left += 10;
if( img_left >= 600 ){
img_left = 0;
img_top += 10;
}
i++;
}
}
//取出自己的圖半透明後再疊到之前做好的朋友組圖上
var me_img_src = $('#me .meimg').attr('src');
var img_me = new Image();
img_me.src = me_img_src;
var canvasme = document.getElementById("canvas_me");
var ctx_me = canvasme.getContext("2d");
ctx_me.globalAlpha = 0.75;
ctx_me.drawImage(img_me, 0, 0,600,600);
ctx.drawImage(canvasme, 0,0,600,600);
canvasme.style.display = 'none';
$('#msg').html('');
});
結果圖:
範例結果: http://excite.978.tw/html5/montage.php
沒有留言:
張貼留言