这篇文章主要介绍了JavaScript+html5 canvas实现本地截图教程,对截图功能感兴趣的小伙伴们可以参考一下

最近有时间了解了下html5的各API,发现新浪微博的头像设置是使用canvas实现截图的,加之前段时间了解了下html5的File API使用File API 之FileReader实现文件上传《JavaScript File API文件上传预览》,更加觉得html5好玩了,想着也试试写写这功能权当学习canvas吧。
下面奉上我自己写的一个demo,代码写得比较少,很多细节不会处理。如果有不得当的地方恳请指教,谢谢啦 ^_^ ^_^
功能实现步奏:

一、获取文件,读取文件并生成url

二、根据容器的大小使用canvas绘制图片

三、使用canvas绘制遮罩层

四、使用canvas绘制裁剪后的图片

五、拖动裁剪框,重新裁剪图片

PS:因为是先把demo写好再写这篇文章的,所以分段贴的代码是直接从代码里面一段段拷的,要留意this对象喔
第一步:获取文件,读取文件并生成url
在这里我是使用html5里面的file api处理本地文件上传的,因为这样可以不需要把图片上传到服务器,再由服务器返回图片地址来做预览,详细请看:使用File API 之FileReader实现文件上传

1 document.getElementById('post_file').onchange = function() {
2   var fileList = this.files[0];
3   var oFReader = new FileReader();
4   oFReader.readAsDataURL(fileList);
5   oFReader.onload = function (oFREvent) { //当读取操作成功完成时调用.
6     postFile.paintImage(oFREvent.target.result);//把预览图片url传给函数
7   };
8 }  

第二步:根据容器的大小使用canvas绘制图片

在上一步使用File API的FileReader已经得到了需要上传图片的地址了,接下来需要使用canvas把这个图片绘制出来。这里为什么不直接插入img而用canvas重新绘制呢,这不是多此一举了吗?其实不然。如果用img直接插入页面,就无法自适应居中了,如果使用canvas绘制图片,不但能使图片自适应居中以及能等比例缩放,并且方便把图片的坐标,尺寸大小传给后来的遮罩层,这样能根据图片的坐标以及图片的尺寸大小来绘制遮罩层。
这里稍微要注意下canvas的drawImage方法。

 1 paintImage: function(url) {
 2   var t = this;
 3   var createCanvas = t.getImage.getContext("2d");
 4   var img = new Image();
 5   img.src = url;
 6   img.onload = function(){
 7   
 8     //等比例缩放图片(如果图片宽高都比容器小,则绘制的图片宽高 = 原图片的宽高。)
 9     //如果图片的宽度或者高度比容器大,则宽度或者高度 = 容器的宽度或者高度,另一高度或者宽度则等比例缩放
10     //t.imgWidth:绘制后图片的宽度;t.imgHeight:绘制后图片的高度;t.px:绘制后图片的X轴;t.py:绘制后图片的Y轴
11     if ( img.width < t.regional.offsetWidth && img.height < t.regional.offsetHeight) {
12       t.imgWidth = img.width;
13       t.imgHeight = img.height;
14   
15     } else {
16       var pWidth = img.width / (img.height / t.regional.offsetHeight);
17       var pHeight = img.height / (img.width / t.regional.offsetWidth);
18       t.imgWidth = img.width > img.height ? t.regional.offsetWidth : pWidth;
19       t.imgHeight = img.height > img.width ? t.regional.offsetHeight : pHeight;
20     }
21     //图片的坐标
22     t.px = (t.regional.offsetWidth - t.imgWidth) / 2 + 'px';
23     t.py = (t.regional.offsetHeight - t.imgHeight) / 2 + 'px';
24       
25     t.getImage.height = t.imgHeight;
26     t.getImage.width = t.imgWidth;
27     t.getImage.style.left = t.px;
28     t.getImage.style.top = t.py;
29   
30     createCanvas.drawImage(img,0,0,t.imgWidth,t.imgHeight);//没用直接插入背景图片而用canvas绘制图片,是为了调整所需框内图片的大小
31     t.imgUrl = t.getImage.toDataURL();//储存canvas绘制的图片地址
32     t.cutImage();
33     t.drag();
34   };
35 },

出来的效果是这样的:

 第三步:使用canvas绘制遮罩层
在上一步中已经把需要裁剪的背景图绘制出来了,现在需要根据背景图的坐标和尺寸来绘制遮罩层覆盖在背景上面,并且使用canvas的clearRect方法清空出一块裁剪区域,使之与不裁剪的地方做明暗对比。
(这里的遮罩层仅仅是用来做显示效果,并没有做裁剪图片的工作。不知道这一步能不能直接去掉?有知道的童鞋麻烦告诉下我。)

 1 //绘制遮罩层:
 2 t.editBox.height = t.imgHeight;
 3 t.editBox.width = t.imgWidth;
 4 t.editBox.style.display = 'block';
 5 t.editBox.style.left = t.px;
 6 t.editBox.style.top = t.py;
 7   
 8 var cover = t.editBox.getContext("2d");
 9 cover.fillStyle = "rgba(0, 0, 0, 0.5)";
10 cover.fillRect (0,0, t.imgWidth, t.imgHeight);
11 cover.clearRect(t.sx, t.sy, t.sHeight, t.sWidth)

第四步:使用canvas绘制裁剪后的图片
在第三步里面,把遮罩层绘制好了,但是遮罩层并没有裁剪的能力,仅仅是用来显示裁剪区域与非裁剪区域的对比而已,所以这里就开始做裁剪图片的功能了。同样使用到canvas的drawImage方法。

 1 //绘制剪切图片:
 2 t.editPic.height = t.sHeight;
 3 t.editPic.width = t.sWidth;
 4 var ctx = t.editPic.getContext('2d');
 5 var images = new Image();
 6 images.src = t.imgUrl;
 7 images.onload = function(){
 8   ctx.drawImage(images,t.sx, t.sy, t.sHeight, t.sWidth, 0, 0, t.sHeight, t.sWidth); //裁剪图片
 9   document.getElementById('show_edit').getElementsByTagName('img')[0].src = t.editPic.toDataURL(); //把裁剪后的图片使用img标签显示出来
10 }

 

第五步:拖动裁剪框,重新裁剪图片
使用截图上传头像功能时我们希望能裁剪到满意的图片,所以裁剪框就需要不停的变动才得以裁剪出完美的图片。前几步已经把裁剪图片的基本功能做出来了,所以现在需要做的就是裁剪框跟进鼠标的移动来实时裁剪图片。

 1 drag: function() {
 2   var t = this;
 3   var draging = false;
 4   var startX = 0;
 5   var startY = 0;
 6   
 7   document.getElementById('cover_box').onmousemove = function(e) {
 8     //获取鼠标到背景图片的距离
 9     var pageX = e.pageX - ( t.regional.offsetLeft + this.offsetLeft );
10     var pageY = e.pageY - ( t.regional.offsetTop + this.offsetTop );
11     //判断鼠标是否在裁剪区域里面:
12     if ( pageX > t.sx && pageX < t.sx + t.sWidth && pageY > t.sy && pageY < t.sy + t.sHeight ) {
13       this.style.cursor = 'move';
14         
15       this.onmousedown = function(){
16         draging = true;
17         //记录上一次截图的坐标
18         t.ex = t.sx;
19         t.ey = t.sy;
20         //记录鼠标按下时候的坐标
21         startX = e.pageX - ( t.regional.offsetLeft + this.offsetLeft );
22         startY = e.pageY - ( t.regional.offsetTop + this.offsetTop );
23       }
24       window.onmouseup = function() {
25         draging = false;
26       }
27         
28       if (draging) {
29         //移动时裁剪区域的坐标 = 上次记录的定位 + (当前鼠标的位置 - 按下鼠标的位置),裁剪区域不能超出遮罩层的区域;
30         if ( t.ex + (pageX - startX) < 0 ) {
31           t.sx = 0;
32         } else if ( t.ex + (pageX - startX) + t.sWidth > t.imgWidth) {
33           t.sx = t.imgWidth - t.sWidth;
34         } else {
35           t.sx = t.ex + (pageX - startX);
36         };
37   
38         if (t.ey + (pageY - startY) < 0) {
39           t.sy = 0;
40         } else if ( t.ey + (pageY - startY) + t.sHeight > t.imgHeight ) {
41           t.sy = t.imgHeight - t.sHeight;
42         } else {
43           t.sy = t.ey + (pageY - startY);
44         }
45   
46         t.cutImage();
47       }
48     } else{
49       this.style.cursor = 'auto';
50     }
51   };
52 }

 

大功告成,图片如下:

 

有童鞋指出,每移动一下鼠标就裁剪一张图片不是很耗性能吗,为什么不用background-position来做预览效果 保存的时候才用canvas裁出来?一听觉得这建议很有道理,所以就在第四步把代码稍微改动了一下。鼠标移动的时候的预览效果是改变图片的background-position,点击保存按钮的时候才裁剪图片,把裁剪下来的图片生成新的url就可以传给服务器啦~~
以下代码是改正过来的,大家有什么其它好的建议欢迎指出来喔 ^_^ ^_^


demo完整代码如下:
注意:因为用的是seajs写的,所以稍微留意下文件的加载情况啦

css:

1 body{text-align:center;}
2 #label{border:1px solid #ccc;background-color:#fff;text-align:center;height:300px; width:300px;margin:20px auto;position:relative;}
3 #get_image{position:absolute;}
4 #edit_pic{position:absolute;display:none;background:#000;}
5 #cover_box{position: absolute;z-index: 9999;display:none;top:0px;left:0px;}
6 #show_edit{margin: 0 auto;display:inline-block;}
7 #show_pic{height:100px;width:100px;border:2px solid #000;overflow:hidden;margin:0 auto;display:inline-block; }

html: 

 1 <input type="file" name="file" id="post_file">
 2 <button id="save_button">保存</button>
 3 <div id="label">
 4   <canvas id="get_image"></canvas>
 5   <p>
 6     <canvas id="cover_box"></canvas>
 7     <canvas id="edit_pic"></canvas>
 8   </p>
 9 </div>
10 <p>
11   <span id="show_edit"></span>
12   <span id="show_pic"><img src=""></span>
13 </p>
14  
15  
16 <script type="text/javascript" src="../../lib/seajs/sea.js"></script>
17 <script type="text/javascript">
18 seajs.use(['_example/fileAPI/index_v2.js'], function(clipFile) {
19   clipFile.init({
20     clipPos: {    //裁剪框的默认尺寸与定位
21       x: 15,
22       y: 15,
23       height: 100,
24       width: 100,
25     },
26   });
27 });
28  
29 </script>

js:

  1 define(function(require, exports, module) {
  2  
  3   'use strict';
  4  
  5   var postFile = {
  6     init: function(options) {
  7       var t = this;
  8       t.regional = document.getElementById('label');
  9       t.getImage = document.getElementById('get_image');
 10       t.clipPic = document.getElementById('edit_pic');
 11       t.coverBox = document.getElementById('cover_box');
 12       t.achieve = document.getElementById('show_edit');
 13  
 14       t.clipPos = options.clipPos;
 15  
 16       //初始化图片基本参数
 17       t.bgPagePos = {    
 18         x: 0,
 19         y: 0,
 20         height: 0,
 21         width: 0
 22       };
 23  
 24       //传进图片
 25       document.getElementById('post_file').addEventListener("change", t.handleFiles, false);
 26  
 27       //点击保存按钮后再裁剪图片
 28       document.getElementById('save_button').onclick = function() {
 29  
 30         //绘制剪切后的图片:
 31         t.clipPic.height = t.clipPos.height;
 32         t.clipPic.width = t.clipPos.width;
 33  
 34         var ctx = t.clipPic.getContext('2d');
 35         var images = new Image();
 36         images.src = t.imgUrl;
 37         images.onload = function(){
 38  
 39           //drawImage(images,相对于裁剪图片的X, 相对于裁剪图片的Y, 裁剪的高度, 裁剪的宽度, 显示在画布的X, 显示在画布的Y, 显示在画布多高, 显示在画布多宽);
 40           ctx.drawImage(images,t.clipPos.x, t.clipPos.y, t.clipPos.height, t.clipPos.width, 0, 0, t.clipPos.height, t.clipPos.width); //裁剪图片
 41            
 42           document.getElementById('show_pic').getElementsByTagName('img')[0].src = t.clipPic.toDataURL();
 43         }
 44       };
 45  
 46       t.drag();
 47     },
 48     handleFiles: function() {
 49  
 50       var fileList = this.files[0];
 51       var oFReader = new FileReader();
 52  
 53       //读取文件内容
 54       oFReader.readAsDataURL(fileList);
 55  
 56       //当读取操作成功完成时调用.
 57       oFReader.onload = function (oFREvent) {
 58  
 59         //把预览图片URL传给函数
 60         postFile.paintImage(oFREvent.target.result);
 61       };
 62     },
 63     paintImage: function(url) {
 64       var t = this;
 65       var createCanvas = t.getImage.getContext("2d");
 66  
 67       var img = new Image();
 68       img.src = url;
 69  
 70       //把传进来的图片进行等比例缩放
 71       img.onload = function(){
 72         //等比例缩放图片(如果图片宽高都比容器小,则绘制的图片宽高 = 原图片的宽高。)
 73         //如果图片的宽度或者高度比容器大,则宽度或者高度 = 容器的宽度或者高度,另一高度或者宽度则等比例缩放
 74  
 75         //t.bgPagePos.width:绘制后图片的宽度;
 76         //t.bgPagePos.height:绘制后图片的高度;
 77         //t.bgPagePos.x:绘制后图片的X轴;
 78         //t.bgPagePos.y:绘制后图片的Y轴
 79         if ( img.width < t.regional.offsetWidth && img.height < t.regional.offsetHeight) {
 80           t.bgPagePos.width = img.width;
 81           t.bgPagePos.height = img.height;
 82  
 83         } else {
 84           var pWidth = img.width / (img.height / t.regional.offsetHeight);
 85           var pHeight = img.height / (img.width / t.regional.offsetWidth);
 86  
 87           t.bgPagePos.width = img.width > img.height ? t.regional.offsetWidth : pWidth;
 88           t.bgPagePos.height = img.height > img.width ? t.regional.offsetHeight : pHeight;
 89         }
 90  
 91         //图片的坐标
 92         t.bgPagePos.x = (t.regional.offsetWidth - t.bgPagePos.width) / 2 + 'px';
 93         t.bgPagePos.y = (t.regional.offsetHeight - t.bgPagePos.height) / 2 + 'px';
 94          
 95         t.getImage.height = t.bgPagePos.height;
 96         t.getImage.width = t.bgPagePos.width;
 97         t.getImage.style.left = t.bgPagePos.x;
 98         t.getImage.style.top = t.bgPagePos.y;
 99  
100         createCanvas.drawImage(img,0,0,t.bgPagePos.width,t.bgPagePos.height);//没用直接插入背景图片而用canvas绘制图片,是为了调整所需框内图片的大小
101          
102         t.imgUrl = t.getImage.toDataURL();//储存canvas绘制的图片地址
103  
104         t.clipImg();
105       };
106     },
107     clipImg: function() {
108       var t = this;
109  
110       //绘制遮罩层:
111       t.coverBox.height = t.bgPagePos.height;
112       t.coverBox.width = t.bgPagePos.width;
113       t.coverBox.style.display = 'block';
114       t.coverBox.style.left = t.bgPagePos.x;
115       t.coverBox.style.top = t.bgPagePos.y;
116  
117       var cover = t.coverBox.getContext("2d");
118       cover.fillStyle = "rgba(0, 0, 0, 0.5)";
119       cover.fillRect (0,0, t.bgPagePos.width, t.bgPagePos.height);
120       cover.clearRect(t.clipPos.x, t.clipPos.y, t.clipPos.height, t.clipPos.width);
121  
122       t.achieve.style.background = 'url(' + t.imgUrl + ')' + -t.clipPos.x + 'px ' + -t.clipPos.y + 'px no-repeat';
123       t.achieve.style.height = t.clipPos.height + 'px';
124       t.achieve.style.width = t.clipPos.width + 'px';
125     },
126     drag: function() {
127       var t = this;
128       var draging = false;
129       var _startPos = null;
130  
131       t.coverBox.onmousemove = function(e) {
132         e = e || window.event;
133  
134         if ( e.pageX == null && e.clientX != null ) {
135  
136           var doc = document.documentElement, body = document.body;
137  
138           e.pageX = e.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
139           e.pageY = e.clientY + (doc && doc.scrollTop || body && body.scrollTop);
140         }
141  
142         //获取鼠标到背景图片的距离
143         var _mousePos = {
144           left: e.pageX - ( t.regional.offsetLeft + this.offsetLeft ),
145           top: e.pageY - ( t.regional.offsetTop + this.offsetTop )
146         }
147  
148         //判断鼠标是否在裁剪区域里面:
149         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 ) {
150           this.style.cursor = 'move';
151            
152           this.onmousedown = function(){
153             draging = true;
154             //记录上一次截图的坐标
155             t.ex = t.clipPos.x;
156             t.ey = t.clipPos.y;
157  
158             //记录鼠标按下时候的坐标
159             _startPos = {
160               left: e.pageX - ( t.regional.offsetLeft + this.offsetLeft ),
161               top: e.pageY - ( t.regional.offsetTop + this.offsetTop )
162             }
163           }
164  
165           if (draging) {
166             //移动时裁剪区域的坐标 = 上次记录的定位 + (当前鼠标的位置 - 按下鼠标的位置),裁剪区域不能超出遮罩层的区域;
167             if ( t.ex + ( _mousePos.left - _startPos.left ) < 0 ) {
168               t.clipPos.x = 0;
169             } else if ( t.ex + ( _mousePos.left - _startPos.left ) + t.clipPos.width > t.bgPagePos.width ) {
170               t.clipPos.x = t.bgPagePos.width - t.clipPos.width;
171             } else {
172               t.clipPos.x = t.ex + ( _mousePos.left - _startPos.left );
173             };
174  
175             if (t.ey + ( _mousePos.top - _startPos.top ) < 0) {
176               t.clipPos.y = 0;
177             } else if ( t.ey + ( _mousePos.top - _startPos.top ) + t.clipPos.height > t.bgPagePos.height ) {
178               t.clipPos.y = t.bgPagePos.height - t.clipPos.height;
179             } else {
180               t.clipPos.y = t.ey + ( _mousePos.top - _startPos.top );
181             }
182  
183             t.clipImg();
184           }
185  
186           document.body.onmouseup = function() {
187             draging = false;
188             document.onmousemove = null;
189             document.onmouseup = null;
190           }
191         } else{
192           this.style.cursor = 'auto';
193         }
194       };
195     }
196   }
197   return postFile;
198 });
View Code

 

以上就是本文的全部内容,希望对大家的学习有所帮助。

转载自http://www.jb51.net/article/79068.htm

 posted on 2017-08-22 17:14  黄小黄的黄  阅读(903)  评论(0编辑  收藏  举报