使用canvas进行图像编辑的实例


Posted in Javascript onAugust 29, 2017

前面的话

本文将分为几个小功能的形式来详细介绍canvas图像编辑

缩放

下面是一张分析图,假设默认情况下,图片和canvas宽高相同。图片的缩放(scale)范围为0.5到3,缩放时改变的是图片的大小和图片的坐标位置

W(宽) = canvas.width * scale
H(高) = canvas.height * scale
x坐标 = (W - canvas.width)/2;
y坐标 = (H - canvas.height)/2;

使用canvas进行图像编辑的实例

因此,代码如下

<canvas id="drawing" >
  <p>The canvas element is not supported!</p>
</canvas>
<br>
<input id="scale-range" min="0.5" max="1.5" step="0.01" type="range" >
<script>
var drawing = document.getElementById('drawing');
if(drawing.getContext){
 var context = drawing.getContext('2d');
 var slider = document.getElementById('scale-range');
 var W = 400;
 var H = 290; 
 drawing.width = W; 
 drawing.height = H;
 var image = new Image();
 image.src="http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/chunfen.jpg";
 image.onload = function(){
  drawImgByScale(slider.value);
  slider.onmousemove = function(){
   drawImgByScale(slider.value);
  }
 }
 function drawImgByScale(scale){
  var imgW = W * scale;
  var imgH = H * scale;
  var dx =(W - imgW)/2;
  var dy =(H - imgH)/2;
  context.clearRect(0,0,W,H);
  context.drawImage(image,dx,dy,imgW,imgH);
 }
} 
</script>

水印

利用canvas可以实现向图片添加水印的功能,先通过file控件的reader选择图片,然后使用canvas添加图片及水印,并且使用toDataURL()和a标签实现添加水印后的图片的下载功能

<canvas id="drawing" >
  <p>The canvas element is not supported!</p>
</canvas>
<div>
 <span>
  <input type="file" id="addImgHelper" >
  <button id="addImg">选择图片</button>
 </span>
 <span>
  <button id="addWaterMark" disabled>添加水印</button> 
  <span>水印文字为</span>
  <input id="waterMarkWords" type="text" value="小火柴的蓝色理想">   
 </span>
 <span>
  <button id="downloadImg" disabled>下载图片</button>
  <a id="downloadImgHelper" href="#" rel="external nofollow" download="带水印图片" ></a>  
 </span>
</div>
<script>
if(drawing.getContext){
 var cxt = drawing.getContext('2d');
 var W,H; 
 addImg.onclick = function(){
  addImgHelper.click();
 }
 addImgHelper.onchange = function(){
  addWaterMark.disabled = true;
  downloadImg.disabled = true;
  var file = addImgHelper.files[0];
  if(file && /image/.test(file.type)){
   var reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function(){
    var img = new Image();
    img.src= reader.result;
    img.onload = function(){
     addWaterMark.disabled = false;
     drawing.width = W = img.width;
     drawing.height = H = img.height;
     cxt.drawImage(img,0,0);
     addWaterMark.onclick = function(){
       downloadImg.disabled = false;
       cxt.clearRect(0,0,W,H);
       cxt.drawImage(img,0,0);  
       var str = waterMarkWords.value;
       cxt.font = "bold 50px Arial";
       cxt.lineWidth = '1';
       cxt.fillStyle = 'rgba(255,255,255,0.5)';
       cxt.textBaseline = "bottom";
       cxt.textAlign = 'end';
       cxt.fillText(str,W-10,H-10,W/2);  
       downloadImg.onclick = function(){
        downloadImgHelper.href = drawing.toDataURL('image/png');
        downloadImgHelper.click();    
       }  
     } 
    }
   }   
  }      
 }        
}
</script>

放大镜

下面来实现一个放大镜的效果,鼠标按下并移动时,显示当前图片区域的放大效果,抬起后效果消失。放大镜效果主要使用离屏canvas的技术,离屏canvas放置的是图片的放大版,而普通canvas则放置图片的正常版

<canvas id="drawing" >
  <p>The canvas element is not supported!</p>
</canvas>
<canvas id="drawingOff" >
  <p>The canvas element is not supported!</p>
</canvas>
<script>
if(drawing.getContext){
 var cxt = drawing.getContext('2d');
 var cxtOff = drawingOff.getContext('2d');
 var W,H; 
 var scale = 1.5; 
 var img = new Image();
 img.src="http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/chunfen.jpg";
 img.onload = function(){
  W = img.width;
  H = img.height;
  drawing.width = W/scale;
  drawing.height = H/scale;
  drawingOff.width = W;
  drawingOff.height = H;
  cxt.drawImage(img,0,0,W/scale,H/scale);
  cxtOff.drawImage(img,0,0);
  drawing.onmousedown = function(e){
   e = e || event;
   var x0 = this.offsetLeft;
   var y0 = this.offsetTop; 
   drawMagnifier(e);
   drawing.onmousemove = function(e){
    drawMagnifier(e);
   }
   document.onmouseup = function(e){
    cxt.clearRect(0,0,W/scale,H/scale);
    cxt.drawImage(img,0,0,W/scale,H/scale);
    drawing.onmousemove = null;
   }    
   function drawMagnifier(e){
    cxt.clearRect(0,0,W/scale,H/scale);
    cxt.drawImage(img,0,0,W/scale,H/scale);
    var x = (e.clientX-x0);
    var y = (e.clientY-y0);    
    var r = 40;
    var dx = x - r;
    var dy = y - r;
    var sx = x*scale - r;
    var sy = y*scale - r;
    cxt.save();
    cxt.beginPath();
    cxt.arc(x,y,r,0,Math.PI*2);
    cxt.lineWidth = 4;
    cxt.strokeStyle = '#069';
    cxt.stroke();
    cxt.clip();
    cxt.drawImage(drawingOff,sx,sy,2*r,2*r,dx,dy,2*r,2*r);
    cxt.restore();     
   }
  }
 } 
}
</script>

滤镜

下面利用canvas的getImageData()方法,获取原始图像数据,通过对图像数据进行修改,然后输出修改后的图像数据

<canvas id="drawing1" >
  <p>The canvas element is not supported!</p>
</canvas>
<canvas id="drawing2" >
  <p>The canvas element is not supported!</p>
</canvas>
<br>
<button id="noGreen">无绿色</button>
<button id="noBlue">无蓝色</button>
<button id="toGrey">灰度</button>
<button id="toBlackWhite">黑白</button>
<button id="reverse">反色</button>
<script>
if(drawing1.getContext){
 var cxt1 = drawing1.getContext('2d');
 var cxt2 = drawing2.getContext('2d');
 var img = new Image();
 img.src="chunfen.jpg";
 img.onload = function(){
  cxt1.drawImage(img,0,0);
  function filter(fn){
   var imageData = cxt1.getImageData(0,0,img.width,img.height); 
   cxt2.clearRect(0,0,drawing2.width,drawing2.height); 
   var data = imageData.data;
   for(var i = 0, len = data.length; i < len; i+=4){
    fn(data,i)
   }
   imageData.data = data;
   cxt2.putImageData(imageData,0,0); 
  }
  function fnNoGreen(data,i){
   data[i+1] = 0;
  }
  function fnNoBlue(data,i){
   data[i+2] = 0;
  } 
  function fnReverse(data,i){
   var red = data[i];
   var green = data[i+1];
   var blue = data[i+2];
   var alpha = data[i+3];
   data[i] = 255 - red;
   data[i+1] = 255 - green;
   data[i+2] = 255 - blue;
  }    
  function fnToGrey(data,i){
   var red = data[i];
   var green = data[i+1];
   var blue = data[i+2];
   var alpha = data[i+3];
   var average = Math.floor((red+green+blue)/3);
   data[i] = data[i+1] = data[i+2] = average;   
  }  
  function fnToBlackWhite(data,i){
   var red = data[i];
   var green = data[i+1];
   var blue = data[i+2];
   var alpha = data[i+3];
   var average = Math.floor((red+green+blue)/3);
   if(average > 255/2){
    var result = 255;
   }else{
    var result = 0;
   }
   data[i] = data[i+1] = data[i+2] = result;    
  }
  toGrey.onclick = function(){
   filter(fnToGrey);
  }
  noGreen.onclick = function(){
   filter(fnNoGreen);
  } 
  noBlue.onclick = function(){
   filter(fnNoBlue);
  } 
  toBlackWhite.onclick = function(){
   filter(fnToBlackWhite);
  }
  reverse.onclick = function(){
   filter(fnReverse);
  } 
 }
}
</script>

马赛克效果

【普通模糊效果】

普通模糊效果不仅需要使用当前像素点,还需要使用周围的像素点,并把这些像素点都赋予平均值

function fnToBlur(n){
   cxt2.clearRect(0,0,drawing2.width,drawing2.height); 
   var imageData = cxt1.getImageData(0,0,drawing2.width,drawing2.height); 
   var tempImageData = imageData;
   var data = imageData.data;
   var tempData = tempImageData.data;
   var blurR = n;
   var totalnum = (2*blurR + 1)*(2*blurR + 1);
   for(var i = blurR; i < drawing2.height - blurR; i++){
    for(var j = blurR; j < drawing2.width - blurR; j++){
     var totalr = 0, totalg = 0, totalb = 0;
     for(var dx = -blurR; dx <= blurR; dx++){
      for(var dy = -blurR; dy <= blurR; dy++){
       var x = i + dx;
       var y = j + dy;
       var p = x*drawing2.width + y;
       totalr += tempData[p*4+0];
       totalg += tempData[p*4+1];
       totalb += tempData[p*4+2];
      }
     }
     var p = i*drawing2.width + j;
     data[p*4+0] = totalr / totalnum;
     data[p*4+1] = totalg / totalnum;
     data[p*4+2] = totalb / totalnum;
    }
   }
   imageData.data = data;
   cxt2.putImageData(imageData,0,0); 
  }

【马赛克效果】

马赛克效果则是把一块区域的值,全部都赋予平均值

function fnToMosaic(n){
   cxt2.clearRect(0,0,drawing2.width,drawing2.height); 
   var imageData = cxt1.getImageData(0,0,drawing2.width,drawing2.height); 
   var tempImageData = imageData;
   var data = imageData.data;
   var tempData = tempImageData.data;
   var size = n;
   var totalnum = size*size;
   for(var i = 0; i < drawing2.height; i+=size){
    for(var j = 0; j < drawing2.width; j+=size){
     var totalr = 0, totalg = 0, totalb = 0;
     for(var dx = 0; dx < size; dx++){
      for(var dy = 0; dy < size; dy++){
       var x = i + dx;
       var y = j + dy;
       var p = x*drawing2.width + y;
       totalr += tempData[p*4+0];
       totalg += tempData[p*4+1];
       totalb += tempData[p*4+2];
      }
     }
     var p = i*drawing2.width + j;
     var resr = totalr / totalnum;
     var resg = totalg / totalnum;
     var resb = totalb / totalnum;
     for(var dx = 0; dx < size; dx++){
      for(var dy = 0; dy < size; dy++){
       var x = i + dx;
       var y = j + dy;
       var p = x*drawing2.width + y;
       data[p*4+0]= resr;
       data[p*4+1]= resg;
       data[p*4+2]= resb;
      }
     }
    }
   }
   imageData.data = data;
   cxt2.putImageData(imageData,0,0); 
  }

下面是一个实例

<canvas id="drawing1" >
  <p>The canvas element is not supported!</p>
</canvas>
<canvas id="drawing2" >
  <p>The canvas element is not supported!</p>
</canvas>
<br>
<button id="toLightBlur">轻度模糊</button>
<button id="toHeavyBlur">重度模糊</button>
<button id="toLightMosaic">轻度马赛克</button>
<button id="toHeavyMosaic">重度马赛克</button>
<script>
if(drawing1.getContext){
 var cxt1 = drawing1.getContext('2d');
 var cxt2 = drawing2.getContext('2d');
 var img = new Image();
 img.src="chunfen.jpg";
 img.onload = function(){
  cxt1.drawImage(img,0,0);
  toLightBlur.onclick = function(){
   fnToBlur(1);
  }
  toHeavyBlur.onclick = function(){
   fnToBlur(3);
  }  
  toLightMosaic.onclick = function(){
   fnToMosaic(4);
  } 
  toHeavyMosaic.onclick = function(){
   fnToMosaic(9);
  }   
  function fnToBlur(n){
   cxt2.clearRect(0,0,drawing2.width,drawing2.height); 
   var imageData = cxt1.getImageData(0,0,drawing2.width,drawing2.height); 
   var tempImageData = imageData;
   var data = imageData.data;
   var tempData = tempImageData.data;
   var blurR = n;
   var totalnum = (2*blurR + 1)*(2*blurR + 1);
   for(var i = blurR; i < drawing2.height - blurR; i++){
    for(var j = blurR; j < drawing2.width - blurR; j++){
     var totalr = 0, totalg = 0, totalb = 0;
     for(var dx = -blurR; dx <= blurR; dx++){
      for(var dy = -blurR; dy <= blurR; dy++){
       var x = i + dx;
       var y = j + dy;
       var p = x*drawing2.width + y;
       totalr += tempData[p*4+0];
       totalg += tempData[p*4+1];
       totalb += tempData[p*4+2];
      }
     }
     var p = i*drawing2.width + j;
     data[p*4+0] = totalr / totalnum;
     data[p*4+1] = totalg / totalnum;
     data[p*4+2] = totalb / totalnum;
    }
   }
   imageData.data = data;
   cxt2.putImageData(imageData,0,0); 
  }
  function fnToMosaic(n){
   cxt2.clearRect(0,0,drawing2.width,drawing2.height); 
   var imageData = cxt1.getImageData(0,0,drawing2.width,drawing2.height); 
   var tempImageData = imageData;
   var data = imageData.data;
   var tempData = tempImageData.data;
   var size = n;
   var totalnum = size*size;
   for(var i = 0; i < drawing2.height; i+=size){
    for(var j = 0; j < drawing2.width; j+=size){
     var totalr = 0, totalg = 0, totalb = 0;
     for(var dx = 0; dx < size; dx++){
      for(var dy = 0; dy < size; dy++){
       var x = i + dx;
       var y = j + dy;
       var p = x*drawing2.width + y;
       totalr += tempData[p*4+0];
       totalg += tempData[p*4+1];
       totalb += tempData[p*4+2];
      }
     }
     var p = i*drawing2.width + j;
     var resr = totalr / totalnum;
     var resg = totalg / totalnum;
     var resb = totalb / totalnum;
     for(var dx = 0; dx < size; dx++){
      for(var dy = 0; dy < size; dy++){
       var x = i + dx;
       var y = j + dy;
       var p = x*drawing2.width + y;
       data[p*4+0]= resr;
       data[p*4+1]= resg;
       data[p*4+2]= resb;
      }
     }
    }
   }
   imageData.data = data;
   cxt2.putImageData(imageData,0,0); 
  }  
 }
}
</script>

以上这篇使用canvas进行图像编辑的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
用javascript实现兼容IE7的类库 IE7_0_9.zip提供下载
Aug 08 Javascript
jquery中防刷IP流量软件影响统计的一点对策
Jul 10 Javascript
javascript表达式和运算符详解
Feb 07 Javascript
vue2.0+koa2+mongodb实现注册登录
Apr 10 Javascript
jQuery/JS监听input输入框值变化实例
Oct 17 jQuery
使用JS location实现搜索框历史记录功能
Dec 23 Javascript
浅谈JavaScript中的“!!”作用
Aug 03 Javascript
vue-quill-editor的使用及个性化定制操作
Aug 04 Javascript
关于element-ui表单中限制输入纯数字的解决方式
Sep 08 Javascript
浅谈Vue static 静态资源路径 和 style问题
Nov 07 Javascript
vue 递归组件的简单使用示例
Jan 14 Vue.js
JavaScript的Set数据结构详解
Feb 18 Javascript
jQuery实现锚点向下平滑滚动特效示例
Aug 29 #jQuery
js使用html2canvas实现屏幕截取的示例代码
Aug 28 #Javascript
JavaScript编写棋盘覆盖代码详解
Aug 28 #Javascript
Angular4开发解决跨域问题详解
Aug 28 #Javascript
JavaScript实现各种排序的代码详解
Aug 28 #Javascript
JS如何设置元素样式的方法示例
Aug 28 #Javascript
weex slider实现滑动底部导航功能
Aug 28 #Javascript
You might like
无线电波是什么?它是怎样传输的?
2021/03/01 无线电
在线短消息收发的程序,不用数据库
2006/10/09 PHP
Win2003+apache+PHP+SqlServer2008 配置生产环境
2014/07/29 PHP
微信公众平台网页授权获取用户基本信息中授权回调域名设置的变动
2014/10/21 PHP
PHP中iconv函数知识汇总
2015/07/02 PHP
PHP+jQuery+Ajax实现分页效果 jPaginate插件的应用
2015/10/09 PHP
浅谈PHP中其他类型转化为Bool类型
2016/03/28 PHP
php+javascript实现的动态显示服务器运行程序进度条功能示例
2017/08/07 PHP
让广告代码不再影响你的网页加载速度
2006/07/07 Javascript
jquery乱码与contentType属性设置问题解决方案
2013/01/07 Javascript
JavaScript实现的使用键盘控制人物走动实例
2014/08/27 Javascript
vue2.0设置proxyTable使用axios进行跨域请求的方法
2017/10/19 Javascript
jquery radio 动态控制选中失效问题的解决方法
2018/02/28 jQuery
使用vuex的state状态对象的5种方式
2018/04/19 Javascript
对vue事件的延迟执行实例讲解
2018/08/28 Javascript
Vue 2.0 中依赖注入 provide/inject组合实战
2019/06/20 Javascript
解决layui数据表格排序图标被超出的表头挤出去的问题
2019/09/19 Javascript
vue中对象数组去重的实现
2020/02/06 Javascript
[50:21]Liquid vs Winstrike 2018国际邀请赛小组赛BO2 第二场
2018/08/19 DOTA
Python递归遍历列表及输出的实现方法
2015/05/19 Python
详解Django中Request对象的相关用法
2015/07/17 Python
python类中super()和__init__()的区别
2016/10/18 Python
python中使用 xlwt 操作excel的常见方法与问题
2019/01/13 Python
在Python中将函数作为另一个函数的参数传入并调用的方法
2019/01/22 Python
浅谈pytorch池化maxpool2D注意事项
2020/02/18 Python
python如何查看安装了的模块
2020/06/23 Python
Doyoueven官网:澳大利亚健身服饰和配饰品牌
2019/03/24 全球购物
工商管理专业学生的自我评价
2013/10/01 职场文书
员工入职担保书范文
2014/04/01 职场文书
电子信息专业应届生自荐信
2014/06/04 职场文书
食堂厨师岗位职责
2014/08/25 职场文书
党的群众路线教育实践活动整改落实情况自查报告
2014/10/28 职场文书
店长岗位职责
2015/02/11 职场文书
2015年学校保卫部工作总结
2015/05/11 职场文书
招商银行收入证明
2015/06/17 职场文书
董事长秘书工作总结
2015/08/14 职场文书