簡易版 html5 撕掉mm的衣服

昨天在csdn閒逛的時候,看到了http://blog.csdn.net/cuixiping/article/details/7161808這篇文章,便嘗試着自己寫一個玩玩,順便貼上寫註釋。

html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>撕掉mm的衣服</title>
<style type="text/css">
html, body
{ margin:0; padding:0; text-align: center; background-color:black }
div
{color:white;}
#canvas
{
border
:solid 1px #CCC;
margin-bottom
: 10px;
}
</style>
<script src="draw.js"></script>
</head>
<body>
<p style="color:yellow">點擊就可以嘗試下面的效果了</p>
<div><canvas id="canvas" width="480" height="320">很抱歉,是時候更換瀏覽器了<a href="http://firefox.com.cn/download/">點擊下載firefox</a></canvas></div>
</body>
</html>

css代碼的實現的效果:使得canvas元素居中顯示,且周圍爲“關燈”效果,凸顯出圖片

 

draw.js

var ready,canvas,context;
var load;
var BRUSH_SIZE=18;//BRUSH_SIZE指的是鼠標表示的畫刷,"橡皮擦"的大小
var img =new Image();
var cimg =new Image();

window.onload=function(){
if(!document.getElementById("canvas").getContext){//若瀏覽器不支持canvas,則返回
return;
}
canvas= document.getElementById("canvas");//獲取canvas元素
context = canvas.getContext('2d');//獲取canvas畫布
loading();
pics =['images/a1.jpg','images/a2.jpg'];//圖片數組,pics[0]爲當前圖片,pics[1]爲替換後的圖片
load=0;//初始化標誌兩幅圖片加載次數的變量
cimg.onload = img.onload = function (){
if(++load==2){//表明兩幅圖均加載完成
initCoverImage();
}
}
cimg.onerror = img.onerror = function (){//有圖像加載過程中發生錯誤
context.clearRect(0,0,canvas.width,canvas.height);
context.font = '12px sans-serif';//顯示字體格式
context.fillStyle = '#00ff00';
context.textAlign = 'center';
context.fillText('Load images failure!', canvas.width>>1, canvas.height-50);//其中canvas>>1典型的右移運算,即除以2
}
//上述所有事件設置完成後,設置圖片的src
cimg.src = pics[0];
img.src = pics[1];
}

function loading(){//設置及顯示
context.clearRect(0,0,canvas.width,canvas.height);//清空canvas窗口
context.fillText('Loading...', canvas.width>>1, canvas.height-50);//若圖片獲取較慢,會顯示loading...
}

function initCoverImage(){//繪製當前圖像
canvas.width = cimg.width;//調整canvas大小,符合真實圖片
canvas.height = cimg.height;
context.drawImage(cimg, 0, 0, canvas.width, canvas.height);
bindEvents();//綁定事件
}

function bindEvents(){
canvas.ontouchstart = canvas.onmousedown = function(e) { ready = true; };//鼠標摁下
canvas.ontouchend = canvas.ontouchcancel = canvas.onmouseup = canvas.onmouseout = (function(e) { ready = false; });//鼠標未摁下
canvas.ontouchmove = canvas.onmousemove = updateCanvas;//相應鼠標的移動事件
}

function updateCanvas(e){
if(!ready) {//鼠標未摁下
return;
}
var r = canvas.getBoundingClientRect();//獲取當前canvas區域的座標
var vx = e.clientX - r.left;//橫向距離
var vy = e.clientY - r.top;//縱向距離

var bs = BRUSH_SIZE;
var bsr = bs/2;

if ( vx < bsr || vy < bsr) {//據canvas邊緣太近,則指定此時"擦拭"無效
return;
}
context.rect(vx-bsr, vy-bsr, bs, bs);//否則圈定當前一塊區域方便被"替換"爲下一幅圖的相同區域
context.drawImage(img, vx-bsr, vy-bsr, bs, bs, vx-bsr, vy-bsr, bs, bs);//替換
}

上面的這個是利用drawImage來覆蓋圖片的形式完成脫衣過程,也可以用IplImage圖像矩陣來替換,原理是一樣的。

這個,大家可以自己嘗試。

(由於實在是搞不到那些mm的圖片,就用自己的照片做個示範,演示下效果^-^)

images/a1.jpg

 

images/a2.jpg

最終效果:

轉載請註明:http://www.cnblogs.com/blue-lg/archive/2011/12/30/2307649.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章