js canvas实现橡皮擦效果


Posted in Javascript onDecember 20, 2018

本文实例为大家分享了canvas实现橡皮擦效果的具体代码,供大家参考,具体内容如下

html部分

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" /> 
<title>My Canvas 0.1</title>
<style type="text/css">
html,body,div,img{
 margin:0;
 padding:0;
}
a,a:hover{
 text-decoration:none;
}
.background{
 width:100%;
 position:fixed;
 top:0;
 left:0;
}
</style>
</head>
 
<body>
<img src="images/background.png" class="background resizeContainer"/>
<div id="J_cover" class="resizeContainer"></div>
<script type="text/javascript" src="js/zepto.js"></script>
<script type="text/javascript" src="js/lottery.js"></script>
<script type="text/javascript">
var canvas = {
 init : function(){
 var self = this;
 var node = document.getElementById('J_cover'),
 canvas_url = 'images/cover.png',
 type = 'image';
 
 var lottery = new Lottery(node, canvas_url, type, window_w, window_h, self.callback);
  lottery.init();
 },
 callback : function(){
 $('#J_cover').hide();
 }
}
var window_h, window_w;
$(document).ready(function(){
 window_w = $(window).width();
 window_h = $(window).height();
 
 $('.resizeContainer').width(window_w).height(window_h);
 
 canvas.init();
});
</script>
</body>
</html>

lottery.js

function Lottery(node, cover, coverType, width, height, drawPercentCallback) {
//node:canvas的id,cover:上面一层的图片地址,coverType:'image'or'color',width:canvas宽, height:canvas高, drawPercentCallback:回调函数
 //canvas
 this.conNode = node;
 
 this.background = null;
 this.backCtx = null;
 
 this.mask = null;
 this.maskCtx = null;
 
 this.lottery = null;
 this.lotteryType = 'image';
 
 this.cover = cover || "#000";
 this.coverType = coverType;
 this.pixlesData = null;
 
 this.width = width;
 this.height = height;
 
 this.lastPosition = null;
 this.drawPercentCallback = drawPercentCallback;
 
 this.vail = false;
}
 
Lottery.prototype = {
 createElement: function(tagName, attributes) {
  var ele = document.createElement(tagName);
  for (var key in attributes) {
   ele.setAttribute(key, attributes[key]);
  }
  return ele;
 },
 
 getTransparentPercent: function(ctx, width, height) {
  var imgData = ctx.getImageData(0, 0, width, height),
   pixles = imgData.data,
   transPixs = [];
 
  for (var i = 0, j = pixles.length; i < j; i += 4) {
   var a = pixles[i + 3];
   if (a < 128) {
    transPixs.push(i);
   }
  }
  return (transPixs.length / (pixles.length / 4) * 100).toFixed(2);
 },
 
 resizeCanvas: function(canvas, width, height) {
  canvas.width = width;
  canvas.height = height;
  canvas.getContext('2d').clearRect(0, 0, width, height);
 },
 
 resizeCanvas_w: function(canvas, width, height) {
  canvas.width = width;
  canvas.height = height;
  canvas.getContext('2d').clearRect(0, 0, width, height);
 
  if (this.vail) this.drawLottery();
  else this.drawMask();
 },
 
 drawPoint: function(x, y, fresh) {
  this.maskCtx.beginPath();
  this.maskCtx.arc(x, y, 20, 0, Math.PI * 2);
  this.maskCtx.fill();
 
  this.maskCtx.beginPath();
 
  this.maskCtx.lineWidth = 60;
  this.maskCtx.lineCap = this.maskCtx.lineJoin = 'round';
 
  if (this.lastPosition) {
   this.maskCtx.moveTo(this.lastPosition[0], this.lastPosition[1]);
  }
  this.maskCtx.lineTo(x, y);
  this.maskCtx.stroke();
 
  this.lastPosition = [x, y];
 
  this.mask.style.zIndex = (this.mask.style.zIndex == 20) ? 21 : 20;
 },
 
 bindEvent: function() {
  var _this = this;
  var device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
  var clickEvtName = device ? 'touchstart' : 'mousedown';
  var moveEvtName = device ? 'touchmove' : 'mousemove';
  if (!device) {
   var isMouseDown = false;
   _this.conNode.addEventListener('mouseup', function(e) {
    e.preventDefault();
 
    isMouseDown = false;
    var per = _this.getTransparentPercent(_this.maskCtx, _this.width, _this.height);
 
    if (per >= 80) {//在大于等于80%的时候调用回调函数
     if (typeof(_this.drawPercentCallback) == 'function') _this.drawPercentCallback();
    }
   }, false);
  } else {
   _this.conNode.addEventListener("touchmove", function(e) {
    if (isMouseDown) {
     e.preventDefault();
    }
    if (e.cancelable) {
     e.preventDefault();
    } else {
     window.event.returnValue = false;
    }
   }, false);
   _this.conNode.addEventListener('touchend', function(e) {
    isMouseDown = false;
    var per = _this.getTransparentPercent(_this.maskCtx, _this.width, _this.height);
    if (per >= 80) {//在大于等于80%的时候调用回调函数
     if (typeof(_this.drawPercentCallback) == 'function') _this.drawPercentCallback();
    }
   }, false);
  }
 
  this.mask.addEventListener(clickEvtName, function(e) {
   e.preventDefault();
 
   isMouseDown = true;
 
   var x = (device ? e.touches[0].pageX : e.pageX || e.x);
   var y = (device ? e.touches[0].pageY : e.pageY || e.y);
 
   _this.drawPoint(x, y, isMouseDown);
  }, false);
 
  this.mask.addEventListener(moveEvtName, function(e) {
   e.preventDefault();
 
   if (!isMouseDown) return false;
   e.preventDefault();
 
   var x = (device ? e.touches[0].pageX : e.pageX || e.x);
   var y = (device ? e.touches[0].pageY : e.pageY || e.y);
 
   _this.drawPoint(x, y, isMouseDown);
  }, false);
 },
 
 drawLottery: function() {
  if (this.lotteryType == 'image') {
   var image = new Image(),
    _this = this;
   image.onload = function() {
    this.width = _this.width;
    this.height = _this.height;
    _this.resizeCanvas(_this.background, _this.width, _this.height);
    _this.backCtx.drawImage(this, 0, 0, _this.width, _this.height);
    _this.drawMask();
   }
   image.src = this.lottery;
  } else if (this.lotteryType == 'text') {
   this.width = this.width;
   this.height = this.height;
   this.resizeCanvas(this.background, this.width, this.height);
   this.backCtx.save();
   this.backCtx.fillStyle = '#FFF';
   this.backCtx.fillRect(0, 0, this.width, this.height);
   this.backCtx.restore();
   this.backCtx.save();
   var fontSize = 30;
   this.backCtx.font = 'Bold ' + fontSize + 'px Arial';
   this.backCtx.textAlign = 'center';
   this.backCtx.fillStyle = '#F60';
   this.backCtx.fillText(this.lottery, this.width / 2, this.height / 2 + fontSize / 2);
   this.backCtx.restore();
   this.drawMask();
  }
 },
 
 drawMask: function() {
  if (this.coverType == 'color') {
   this.maskCtx.fillStyle = this.cover;
   this.maskCtx.fillRect(0, 0, this.width, this.height);
   this.maskCtx.globalCompositeOperation = 'destination-out';
  } else if (this.coverType == 'image') {
   var image = new Image(),
    _this = this;
   image.onload = function() {
    _this.resizeCanvas(_this.mask, _this.width, _this.height);
 
    var android = (/android/i.test(navigator.userAgent.toLowerCase()));
 
    _this.maskCtx.globalAlpha = 1;//上面一层的透明度,1为不透明
    _this.maskCtx.drawImage(this, 0, 0, this.width, this.height, 0, 0, _this.width, _this.height);
 
    //---以下一段为在上面一层上写字
    // var fontSize = 50;
    // var txt = '123123';
    // var gradient = _this.maskCtx.createLinearGradient(0, 0, _this.width, 0);
    // gradient.addColorStop("0", "#fff");
    // gradient.addColorStop("1.0", "#000");
 
    // _this.maskCtx.font = 'Bold ' + fontSize + 'px Arial';
    // _this.maskCtx.textAlign = 'left';
    // _this.maskCtx.fillStyle = gradient;
    // _this.maskCtx.fillText(txt, _this.width / 2 - _this.maskCtx.measureText(txt).width / 2, 100);
 
    // _this.maskCtx.globalAlpha = 1;
 
    _this.maskCtx.globalCompositeOperation = 'destination-out';
   }
   image.src = this.cover;
  }
 },
 
 init: function(lottery, lotteryType) {
  if (lottery) {
   this.lottery = lottery;
   this.lottery.width = this.width;
   this.lottery.height = this.height;
   this.lotteryType = lotteryType || 'image';
 
   this.vail = true;
  }
  if (this.vail) {
   this.background = this.background || this.createElement('canvas', {
    style: 'position:fixed;top:0;left:0;background-color:transparent;'
   });
  }
 
  this.mask = this.mask || this.createElement('canvas', {
   style: 'position:fixed;top:0;left:0;background-color:transparent;'
  });
  this.mask.style.zIndex = 20;
 
  if (!this.conNode.innerHTML.replace(/[\w\W]| /g, '')) {
   if (this.vail) this.conNode.appendChild(this.background);
   this.conNode.appendChild(this.mask);
   this.bindEvent();
  }
  if (this.vail) this.backCtx = this.backCtx || this.background.getContext('2d');
  this.maskCtx = this.maskCtx || this.mask.getContext('2d');
 
  if (this.vail) this.drawLottery();
  else this.drawMask();
 
  var _this = this;
  window.addEventListener('resize', function() {
   _this.width = document.documentElement.clientWidth;
   _this.height = document.documentElement.clientHeight;
 
   _this.resizeCanvas_w(_this.mask, _this.width, _this.height);
  }, false);
 }
}

另一个zepto.js是库函数文件,可网上自行查找

出来的效果如图

js canvas实现橡皮擦效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
IE和Firefox在JavaScript应用中的兼容性探讨
Apr 01 Javascript
javascript 动态加载 css 方法总结
Jul 11 Javascript
jQuery学习2 选择器的使用说明
Feb 07 Javascript
cloudgamer出品ImageZoom 图片放大效果
Apr 01 Javascript
jquery获取被勾选的checked(选中)的那一行的3列和4列的值
Jul 04 Javascript
jsonp跨域请求数据实现手机号码查询实例分析
Dec 12 Javascript
jQuery插件WebUploader实现文件上传
Nov 07 Javascript
Bootstrap3下拉菜单的实现
Feb 22 Javascript
JS实现的简单拖拽购物车功能示例【附源码下载】
Jan 03 Javascript
微信小程序实现多行文字超出部分省略号显示功能
Oct 23 Javascript
解决vue语法会有延迟加载显现{{xxx}}的问题
Nov 14 Javascript
Vue 监听元素前后变化值实例
Jul 29 Javascript
浅谈VueJS SSR 后端绘制内存泄漏的相关解决经验
Dec 20 #Javascript
Cocos2d实现刮刮卡效果
Dec 20 #Javascript
浅谈Fetch 数据交互方式
Dec 20 #Javascript
cocos2dx+lua实现橡皮擦功能
Dec 20 #Javascript
element-ui table span-method(行合并)的实现代码
Dec 20 #Javascript
fetch 如何实现请求数据
Dec 20 #Javascript
JS闭包经典实例详解
Dec 20 #Javascript
You might like
php模板之Phpbean的目录结构
2008/01/10 PHP
比较全的PHP 会话(session 时间设定)使用入门代码
2008/06/05 PHP
PHP编程过程中需要了解的this,self,parent的区别
2009/12/30 PHP
php ftp文件上传函数(基础版)
2010/06/03 PHP
ThinkPHP利用PHPMailer实现邮件发送实现代码
2013/09/26 PHP
thinkPHP5.0框架模块设计详解
2017/03/18 PHP
关于PHP5.6+版本“No input file specified”问题的解决
2019/12/11 PHP
脚本收藏iframe
2006/07/21 Javascript
Javascript 判断 object 的特定类转载
2007/02/01 Javascript
可在线编辑网页文字效果代码(单击)
2013/03/02 Javascript
『jQuery』.html(),.text()和.val()的概述及使用
2013/04/22 Javascript
Web表单提交之disabled问题js解决方法
2015/01/13 Javascript
分享一些常用的jQuery动画事件和动画函数
2015/11/27 Javascript
学习javascript文件加载优化
2016/02/19 Javascript
jQuery实现验证年龄简单思路
2016/02/24 Javascript
vue自定义指令实现v-tap插件
2016/11/03 Javascript
JS新包管理工具yarn和npm的对比与使用入门
2016/12/09 Javascript
Extjs gridpanel 中的checkbox(复选框)根据某行的条件不能选中的解决方法
2017/02/17 Javascript
使用Bootstrap + Vue.js实现表格的动态展示、新增和删除功能
2017/11/27 Javascript
vue translate peoject实现在线翻译功能【新手必看】
2018/06/07 Javascript
轻松解决JavaScript定时器越走越快的问题
2019/05/13 Javascript
简单了解TypeScript中如何继承 Error 类
2019/06/21 Javascript
python 数据的清理行为实例详解
2017/07/12 Python
python实现隐马尔科夫模型HMM
2018/03/25 Python
Python语言快速上手学习方法
2018/12/14 Python
python3 小数位的四舍五入(用两种方法解决round 遇5不进)
2019/04/11 Python
pandas将多个dataframe以多个sheet的形式保存到一个excel文件中
2019/10/10 Python
使用python动态生成波形曲线的实现
2019/12/04 Python
python 负数取模运算实例
2020/06/03 Python
如何使用html5与css3完成google涂鸦动画
2012/12/16 HTML / CSS
运动会四百米广播稿
2014/01/19 职场文书
邀请书格式范文
2015/02/02 职场文书
2015中秋节晚会开场白
2015/07/30 职场文书
浅谈Nginx 中的两种限流方式
2021/03/31 Servers
SpringBoot工程下使用OpenFeign的坑及解决
2021/07/02 Java/Android
利用For循环遍历Python字典的三种方法实例
2022/03/25 Python