JavaScript+html5 canvas實(shí)現(xiàn)本地截圖教程
最近有時(shí)間了解了下html5的各API,發(fā)現(xiàn)新浪微博的頭像設(shè)置是使用canvas實(shí)現(xiàn)截圖的,加之前段時(shí)間了解了下html5的File API使用File API 之FileReader實(shí)現(xiàn)文件上傳《JavaScript File API文件上傳預(yù)覽》,更加覺得html5好玩了,想著也試試寫寫這功能權(quán)當(dāng)學(xué)習(xí)canvas吧。
下面奉上我自己寫的一個(gè)demo,代碼寫得比較少,很多細(xì)節(jié)不會(huì)處理。如果有不得當(dāng)?shù)牡胤綉┱?qǐng)指教,謝謝啦 ^_^ ^_^
功能實(shí)現(xiàn)步奏:
- 一、獲取文件,讀取文件并生成url
- 二、根據(jù)容器的大小使用canvas繪制圖片
- 三、使用canvas繪制遮罩層
- 四、使用canvas繪制裁剪后的圖片
- 五、拖動(dòng)裁剪框,重新裁剪圖片
PS:因?yàn)槭窍劝裠emo寫好再寫這篇文章的,所以分段貼的代碼是直接從代碼里面一段段拷的,要留意this對(duì)象喔
第一步:獲取文件,讀取文件并生成url
在這里我是使用html5里面的file api處理本地文件上傳的,因?yàn)檫@樣可以不需要把圖片上傳到服務(wù)器,再由服務(wù)器返回圖片地址來(lái)做預(yù)覽,詳細(xì)請(qǐng)看:使用File API 之FileReader實(shí)現(xiàn)文件上傳
document.getElementById('post_file').onchange = function() {
var fileList = this.files[0];
var oFReader = new FileReader();
oFReader.readAsDataURL(fileList);
oFReader.onload = function (oFREvent) { //當(dāng)讀取操作成功完成時(shí)調(diào)用.
postFile.paintImage(oFREvent.target.result);//把預(yù)覽圖片url傳給函數(shù)
};
}
第二步:根據(jù)容器的大小使用canvas繪制圖片
在上一步使用File API的FileReader已經(jīng)得到了需要上傳圖片的地址了,接下來(lái)需要使用canvas把這個(gè)圖片繪制出來(lái)。這里為什么不直接插入img而用canvas重新繪制呢,這不是多此一舉了嗎?其實(shí)不然。如果用img直接插入頁(yè)面,就無(wú)法自適應(yīng)居中了,如果使用canvas繪制圖片,不但能使圖片自適應(yīng)居中以及能等比例縮放,并且方便把圖片的坐標(biāo),尺寸大小傳給后來(lái)的遮罩層,這樣能根據(jù)圖片的坐標(biāo)以及圖片的尺寸大小來(lái)繪制遮罩層。
這里稍微要注意下canvas的drawImage方法。
paintImage: function(url) {
var t = this;
var createCanvas = t.getImage.getContext("2d");
var img = new Image();
img.src = url;
img.onload = function(){
//等比例縮放圖片(如果圖片寬高都比容器小,則繪制的圖片寬高 = 原圖片的寬高。)
//如果圖片的寬度或者高度比容器大,則寬度或者高度 = 容器的寬度或者高度,另一高度或者寬度則等比例縮放
//t.imgWidth:繪制后圖片的寬度;t.imgHeight:繪制后圖片的高度;t.px:繪制后圖片的X軸;t.py:繪制后圖片的Y軸
if ( img.width < t.regional.offsetWidth && img.height < t.regional.offsetHeight) {
t.imgWidth = img.width;
t.imgHeight = img.height;
} else {
var pWidth = img.width / (img.height / t.regional.offsetHeight);
var pHeight = img.height / (img.width / t.regional.offsetWidth);
t.imgWidth = img.width > img.height ? t.regional.offsetWidth : pWidth;
t.imgHeight = img.height > img.width ? t.regional.offsetHeight : pHeight;
}
//圖片的坐標(biāo)
t.px = (t.regional.offsetWidth - t.imgWidth) / 2 + 'px';
t.py = (t.regional.offsetHeight - t.imgHeight) / 2 + 'px';
t.getImage.height = t.imgHeight;
t.getImage.width = t.imgWidth;
t.getImage.style.left = t.px;
t.getImage.style.top = t.py;
createCanvas.drawImage(img,0,0,t.imgWidth,t.imgHeight);//沒(méi)用直接插入背景圖片而用canvas繪制圖片,是為了調(diào)整所需框內(nèi)圖片的大小
t.imgUrl = t.getImage.toDataURL();//儲(chǔ)存canvas繪制的圖片地址
t.cutImage();
t.drag();
};
},
出來(lái)的效果是這樣的:

第三步:使用canvas繪制遮罩層
在上一步中已經(jīng)把需要裁剪的背景圖繪制出來(lái)了,現(xiàn)在需要根據(jù)背景圖的坐標(biāo)和尺寸來(lái)繪制遮罩層覆蓋在背景上面,并且使用canvas的clearRect方法清空出一塊裁剪區(qū)域,使之與不裁剪的地方做明暗對(duì)比。
(這里的遮罩層僅僅是用來(lái)做顯示效果,并沒(méi)有做裁剪圖片的工作。不知道這一步能不能直接去掉?有知道的童鞋麻煩告訴下我。)
//繪制遮罩層:
t.editBox.height = t.imgHeight;
t.editBox.width = t.imgWidth;
t.editBox.style.display = 'block';
t.editBox.style.left = t.px;
t.editBox.style.top = t.py;
var cover = t.editBox.getContext("2d");
cover.fillStyle = "rgba(0, 0, 0, 0.5)";
cover.fillRect (0,0, t.imgWidth, t.imgHeight);
cover.clearRect(t.sx, t.sy, t.sHeight, t.sWidth);
第四步:使用canvas繪制裁剪后的圖片
在第三步里面,把遮罩層繪制好了,但是遮罩層并沒(méi)有裁剪的能力,僅僅是用來(lái)顯示裁剪區(qū)域與非裁剪區(qū)域的對(duì)比而已,所以這里就開始做裁剪圖片的功能了。同樣使用到canvas的drawImage方法。
//繪制剪切圖片:
t.editPic.height = t.sHeight;
t.editPic.width = t.sWidth;
var ctx = t.editPic.getContext('2d');
var images = new Image();
images.src = t.imgUrl;
images.onload = function(){
ctx.drawImage(images,t.sx, t.sy, t.sHeight, t.sWidth, 0, 0, t.sHeight, t.sWidth); //裁剪圖片
document.getElementById('show_edit').getElementsByTagName('img')[0].src = t.editPic.toDataURL(); //把裁剪后的圖片使用img標(biāo)簽顯示出來(lái)
}
第五步:拖動(dòng)裁剪框,重新裁剪圖片
使用截圖上傳頭像功能時(shí)我們希望能裁剪到滿意的圖片,所以裁剪框就需要不停的變動(dòng)才得以裁剪出完美的圖片。前幾步已經(jīng)把裁剪圖片的基本功能做出來(lái)了,所以現(xiàn)在需要做的就是裁剪框跟進(jìn)鼠標(biāo)的移動(dòng)來(lái)實(shí)時(shí)裁剪圖片。
drag: function() {
var t = this;
var draging = false;
var startX = 0;
var startY = 0;
document.getElementById('cover_box').onmousemove = function(e) {
//獲取鼠標(biāo)到背景圖片的距離
var pageX = e.pageX - ( t.regional.offsetLeft + this.offsetLeft );
var pageY = e.pageY - ( t.regional.offsetTop + this.offsetTop );
//判斷鼠標(biāo)是否在裁剪區(qū)域里面:
if ( pageX > t.sx && pageX < t.sx + t.sWidth && pageY > t.sy && pageY < t.sy + t.sHeight ) {
this.style.cursor = 'move';
this.onmousedown = function(){
draging = true;
//記錄上一次截圖的坐標(biāo)
t.ex = t.sx;
t.ey = t.sy;
//記錄鼠標(biāo)按下時(shí)候的坐標(biāo)
startX = e.pageX - ( t.regional.offsetLeft + this.offsetLeft );
startY = e.pageY - ( t.regional.offsetTop + this.offsetTop );
}
window.onmouseup = function() {
draging = false;
}
if (draging) {
//移動(dòng)時(shí)裁剪區(qū)域的坐標(biāo) = 上次記錄的定位 + (當(dāng)前鼠標(biāo)的位置 - 按下鼠標(biāo)的位置),裁剪區(qū)域不能超出遮罩層的區(qū)域;
if ( t.ex + (pageX - startX) < 0 ) {
t.sx = 0;
} else if ( t.ex + (pageX - startX) + t.sWidth > t.imgWidth) {
t.sx = t.imgWidth - t.sWidth;
} else {
t.sx = t.ex + (pageX - startX);
};
if (t.ey + (pageY - startY) < 0) {
t.sy = 0;
} else if ( t.ey + (pageY - startY) + t.sHeight > t.imgHeight ) {
t.sy = t.imgHeight - t.sHeight;
} else {
t.sy = t.ey + (pageY - startY);
}
t.cutImage();
}
} else{
this.style.cursor = 'auto';
}
};
}
大功告成,圖片如下:

有童鞋指出,每移動(dòng)一下鼠標(biāo)就裁剪一張圖片不是很耗性能嗎,為什么不用background-position來(lái)做預(yù)覽效果 保存的時(shí)候才用canvas裁出來(lái)?一聽覺得這建議很有道理,所以就在第四步把代碼稍微改動(dòng)了一下。鼠標(biāo)移動(dòng)的時(shí)候的預(yù)覽效果是改變圖片的background-position,點(diǎn)擊保存按鈕的時(shí)候才裁剪圖片,把裁剪下來(lái)的圖片生成新的url就可以傳給服務(wù)器啦~~
以下代碼是改正過(guò)來(lái)的,大家有什么其它好的建議歡迎指出來(lái)喔 ^_^ ^_^
demo完整代碼如下:
注意:因?yàn)橛玫氖莝eajs寫的,所以稍微留意下文件的加載情況啦
css:
body{text-align:center;}
#label{border:1px solid #ccc;background-color:#fff;text-align:center;height:300px; width:300px;margin:20px auto;position:relative;}
#get_image{position:absolute;}
#edit_pic{position:absolute;display:none;background:#000;}
#cover_box{position: absolute;z-index: 9999;display:none;top:0px;left:0px;}
#show_edit{margin: 0 auto;display:inline-block;}
#show_pic{height:100px;width:100px;border:2px solid #000;overflow:hidden;margin:0 auto;display:inline-block; }
html:
<input type="file" name="file" id="post_file">
<button id="save_button">保存</button>
<div id="label">
<canvas id="get_image"></canvas>
<p>
<canvas id="cover_box"></canvas>
<canvas id="edit_pic"></canvas>
</p>
</div>
<p>
<span id="show_edit"></span>
<span id="show_pic"><img src=""></span>
</p>
<script type="text/javascript" src="../../lib/seajs/sea.js"></script>
<script type="text/javascript">
seajs.use(['_example/fileAPI/index_v2.js'], function(clipFile) {
clipFile.init({
clipPos: { //裁剪框的默認(rèn)尺寸與定位
x: 15,
y: 15,
height: 100,
width: 100,
},
});
});
</script>
js:
define(function(require, exports, module) {
'use strict';
var postFile = {
init: function(options) {
var t = this;
t.regional = document.getElementById('label');
t.getImage = document.getElementById('get_image');
t.clipPic = document.getElementById('edit_pic');
t.coverBox = document.getElementById('cover_box');
t.achieve = document.getElementById('show_edit');
t.clipPos = options.clipPos;
//初始化圖片基本參數(shù)
t.bgPagePos = {
x: 0,
y: 0,
height: 0,
width: 0
};
//傳進(jìn)圖片
document.getElementById('post_file').addEventListener("change", t.handleFiles, false);
//點(diǎn)擊保存按鈕后再裁剪圖片
document.getElementById('save_button').onclick = function() {
//繪制剪切后的圖片:
t.clipPic.height = t.clipPos.height;
t.clipPic.width = t.clipPos.width;
var ctx = t.clipPic.getContext('2d');
var images = new Image();
images.src = t.imgUrl;
images.onload = function(){
//drawImage(images,相對(duì)于裁剪圖片的X, 相對(duì)于裁剪圖片的Y, 裁剪的高度, 裁剪的寬度, 顯示在畫布的X, 顯示在畫布的Y, 顯示在畫布多高, 顯示在畫布多寬);
ctx.drawImage(images,t.clipPos.x, t.clipPos.y, t.clipPos.height, t.clipPos.width, 0, 0, t.clipPos.height, t.clipPos.width); //裁剪圖片
document.getElementById('show_pic').getElementsByTagName('img')[0].src = t.clipPic.toDataURL();
}
};
t.drag();
},
handleFiles: function() {
var fileList = this.files[0];
var oFReader = new FileReader();
//讀取文件內(nèi)容
oFReader.readAsDataURL(fileList);
//當(dāng)讀取操作成功完成時(shí)調(diào)用.
oFReader.onload = function (oFREvent) {
//把預(yù)覽圖片URL傳給函數(shù)
postFile.paintImage(oFREvent.target.result);
};
},
paintImage: function(url) {
var t = this;
var createCanvas = t.getImage.getContext("2d");
var img = new Image();
img.src = url;
//把傳進(jìn)來(lái)的圖片進(jìn)行等比例縮放
img.onload = function(){
//等比例縮放圖片(如果圖片寬高都比容器小,則繪制的圖片寬高 = 原圖片的寬高。)
//如果圖片的寬度或者高度比容器大,則寬度或者高度 = 容器的寬度或者高度,另一高度或者寬度則等比例縮放
//t.bgPagePos.width:繪制后圖片的寬度;
//t.bgPagePos.height:繪制后圖片的高度;
//t.bgPagePos.x:繪制后圖片的X軸;
//t.bgPagePos.y:繪制后圖片的Y軸
if ( img.width < t.regional.offsetWidth && img.height < t.regional.offsetHeight) {
t.bgPagePos.width = img.width;
t.bgPagePos.height = img.height;
} else {
var pWidth = img.width / (img.height / t.regional.offsetHeight);
var pHeight = img.height / (img.width / t.regional.offsetWidth);
t.bgPagePos.width = img.width > img.height ? t.regional.offsetWidth : pWidth;
t.bgPagePos.height = img.height > img.width ? t.regional.offsetHeight : pHeight;
}
//圖片的坐標(biāo)
t.bgPagePos.x = (t.regional.offsetWidth - t.bgPagePos.width) / 2 + 'px';
t.bgPagePos.y = (t.regional.offsetHeight - t.bgPagePos.height) / 2 + 'px';
t.getImage.height = t.bgPagePos.height;
t.getImage.width = t.bgPagePos.width;
t.getImage.style.left = t.bgPagePos.x;
t.getImage.style.top = t.bgPagePos.y;
createCanvas.drawImage(img,0,0,t.bgPagePos.width,t.bgPagePos.height);//沒(méi)用直接插入背景圖片而用canvas繪制圖片,是為了調(diào)整所需框內(nèi)圖片的大小
t.imgUrl = t.getImage.toDataURL();//儲(chǔ)存canvas繪制的圖片地址
t.clipImg();
};
},
clipImg: function() {
var t = this;
//繪制遮罩層:
t.coverBox.height = t.bgPagePos.height;
t.coverBox.width = t.bgPagePos.width;
t.coverBox.style.display = 'block';
t.coverBox.style.left = t.bgPagePos.x;
t.coverBox.style.top = t.bgPagePos.y;
var cover = t.coverBox.getContext("2d");
cover.fillStyle = "rgba(0, 0, 0, 0.5)";
cover.fillRect (0,0, t.bgPagePos.width, t.bgPagePos.height);
cover.clearRect(t.clipPos.x, t.clipPos.y, t.clipPos.height, t.clipPos.width);
t.achieve.style.background = 'url(' + t.imgUrl + ')' + -t.clipPos.x + 'px ' + -t.clipPos.y + 'px no-repeat';
t.achieve.style.height = t.clipPos.height + 'px';
t.achieve.style.width = t.clipPos.width + 'px';
},
drag: function() {
var t = this;
var draging = false;
var _startPos = null;
t.coverBox.onmousemove = function(e) {
e = e || window.event;
if ( e.pageX == null && e.clientX != null ) {
var doc = document.documentElement, body = document.body;
e.pageX = e.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
e.pageY = e.clientY + (doc && doc.scrollTop || body && body.scrollTop);
}
//獲取鼠標(biāo)到背景圖片的距離
var _mousePos = {
left: e.pageX - ( t.regional.offsetLeft + this.offsetLeft ),
top: e.pageY - ( t.regional.offsetTop + this.offsetTop )
}
//判斷鼠標(biāo)是否在裁剪區(qū)域里面:
if ( _mousePos.left > t.clipPos.x && _mousePos.left < t.clipPos.x + t.clipPos.width && _mousePos.top > t.clipPos.y && _mousePos.top < t.clipPos.y + t.clipPos.height ) {
this.style.cursor = 'move';
this.onmousedown = function(){
draging = true;
//記錄上一次截圖的坐標(biāo)
t.ex = t.clipPos.x;
t.ey = t.clipPos.y;
//記錄鼠標(biāo)按下時(shí)候的坐標(biāo)
_startPos = {
left: e.pageX - ( t.regional.offsetLeft + this.offsetLeft ),
top: e.pageY - ( t.regional.offsetTop + this.offsetTop )
}
}
if (draging) {
//移動(dòng)時(shí)裁剪區(qū)域的坐標(biāo) = 上次記錄的定位 + (當(dāng)前鼠標(biāo)的位置 - 按下鼠標(biāo)的位置),裁剪區(qū)域不能超出遮罩層的區(qū)域;
if ( t.ex + ( _mousePos.left - _startPos.left ) < 0 ) {
t.clipPos.x = 0;
} else if ( t.ex + ( _mousePos.left - _startPos.left ) + t.clipPos.width > t.bgPagePos.width ) {
t.clipPos.x = t.bgPagePos.width - t.clipPos.width;
} else {
t.clipPos.x = t.ex + ( _mousePos.left - _startPos.left );
};
if (t.ey + ( _mousePos.top - _startPos.top ) < 0) {
t.clipPos.y = 0;
} else if ( t.ey + ( _mousePos.top - _startPos.top ) + t.clipPos.height > t.bgPagePos.height ) {
t.clipPos.y = t.bgPagePos.height - t.clipPos.height;
} else {
t.clipPos.y = t.ey + ( _mousePos.top - _startPos.top );
}
t.clipImg();
}
document.body.onmouseup = function() {
draging = false;
document.onmousemove = null;
document.onmouseup = null;
}
} else{
this.style.cursor = 'auto';
}
};
}
}
return postFile;
});
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
- 純JavaScript實(shí)現(xiàn)HTML5 Canvas六種特效濾鏡示例
- JavaScript+html5 canvas實(shí)現(xiàn)圖片破碎重組動(dòng)畫特效
- 教你用幾十行js實(shí)現(xiàn)很炫的canvas交互特效
- js canvas實(shí)現(xiàn)星空連線背景特效
- js canvas實(shí)現(xiàn)隨機(jī)粒子特效
- javascript結(jié)合html5 canvas實(shí)現(xiàn)(可調(diào)畫筆顏色/粗細(xì)/橡皮)的涂鴉板
- Javascript保存網(wǎng)頁(yè)為圖片借助于html2canvas庫(kù)實(shí)現(xiàn)
- js+canvas實(shí)現(xiàn)滑動(dòng)拼圖驗(yàn)證碼功能
- JS+Canvas 實(shí)現(xiàn)下雨下雪效果
- html5 canvas js(數(shù)字時(shí)鐘)實(shí)例代碼
- js和canvas繪制圓形金屬質(zhì)感特效
相關(guān)文章
JavaScript拆分字符串時(shí)產(chǎn)生空字符的解決方案
使用JavaScript的split方法拆分字符串時(shí)出現(xiàn)一些空字符串"",尤其是當(dāng)使用正則表達(dá)式作為分隔符的時(shí)候。那么,產(chǎn)生這些空字符串的原因是什么?又該如何來(lái)處理呢,這就是今天我們要探討的問(wèn)題2014-09-09
利用JS實(shí)現(xiàn)二叉樹遍歷算法實(shí)例代碼
眾所周知javascript語(yǔ)言中只提供了幾種基本類型的數(shù)據(jù)類型,而二叉樹是一種數(shù)據(jù)結(jié)構(gòu),在一些查詢等操作中能提供較好的性能,這篇文章主要給大家介紹了關(guān)于利用JS實(shí)現(xiàn)二叉樹遍歷算法的相關(guān)資料,需要的朋友可以參考下2021-11-11
JS實(shí)現(xiàn)購(gòu)物車中商品總價(jià)計(jì)算
這篇文章主要為大家詳細(xì)介紹了JS實(shí)現(xiàn)購(gòu)物車中商品總價(jià)的計(jì)算 ,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-03-03
JavaScript遞歸函數(shù)定義與用法實(shí)例分析
這篇文章主要介紹了JavaScript遞歸函數(shù)定義與用法,結(jié)合實(shí)例形式分析了javascript遞歸的原理、函數(shù)定義、使用方法及操作注意事項(xiàng),需要的朋友可以參考下2019-01-01
js實(shí)現(xiàn)鼠標(biāo)感應(yīng)向下滑動(dòng)隱藏菜單的方法
這篇文章主要介紹了js實(shí)現(xiàn)鼠標(biāo)感應(yīng)向下滑動(dòng)隱藏菜單的方法,涉及javascript操作鼠標(biāo)事件的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-02-02
JavaScript簡(jiǎn)單計(jì)算人的年齡示例
這篇文章主要介紹了JavaScript簡(jiǎn)單計(jì)算人的年齡,涉及簡(jiǎn)單的javascript字符串轉(zhuǎn)換及日期運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2017-04-04

