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 相关文章推荐
window resize和scroll事件的基本优化思路
Apr 29 Javascript
jQuery学习笔记之基础中的基础
Jan 19 Javascript
详解AngularJS中的表达式使用
Jun 16 Javascript
JS与HTML结合使用marquee标签实现无缝滚动效果代码
Jul 05 Javascript
vuejs动态组件给子组件传递数据的方法详解
Sep 09 Javascript
JavaScript中关键字 in 的使用方法详解
Oct 17 Javascript
ASP.NET jquery ajax传递参数的实例
Nov 02 Javascript
Angular.js实现注册系统的实例详解
Dec 18 Javascript
jquery.tableSort.js表格排序插件使用方法详解
Aug 12 Javascript
使用Vue如何写一个双向数据绑定(面试常见)
Apr 20 Javascript
Node.js原生api搭建web服务器的方法步骤
Feb 15 Javascript
微信小程序indexOf的替换方法(推荐)
Jan 14 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个人网站架设连环讲(一)
2006/10/09 PHP
幻宇的层模拟窗口效果-提供演示和下载
2007/01/20 Javascript
js 与或运算符 || &amp;&amp; 妙用
2009/12/09 Javascript
JavaScript 判断判断某个对象是Object还是一个Array
2010/01/28 Javascript
Javascript和Java获取各种form表单信息的简单实例
2014/02/14 Javascript
jqGrid读取选择的多行的某个属性代码
2014/05/18 Javascript
jQuery中:header选择器用法实例
2014/12/29 Javascript
jQuery中add()方法用法实例
2015/01/08 Javascript
Javascript中apply、call、bind的巧妙使用
2016/08/18 Javascript
基于javascript实现的快速排序
2016/12/02 Javascript
使用node.js搭建服务器
2017/05/20 Javascript
vue路由守卫+登录态管理实例分析
2019/05/21 Javascript
layui--select使用以及下拉框实现键盘选择的例子
2019/09/24 Javascript
js实现微信聊天界面
2020/08/09 Javascript
Vue项目配置跨域访问和代理proxy设置方式
2020/09/08 Javascript
[53:20]2018DOTA2亚洲邀请赛 4.1 小组赛 A组加赛 VG vs OG
2018/04/03 DOTA
Python字符串、元组、列表、字典互相转换的方法
2016/01/23 Python
Python 描述符(Descriptor)入门
2016/11/20 Python
Python中生成Epoch的方法
2017/04/26 Python
详解python中 os._exit() 和 sys.exit(), exit(0)和exit(1) 的用法和区别
2017/06/23 Python
Windows平台Python连接sqlite3数据库的方法分析
2017/07/12 Python
python 与服务器的共享文件夹交互方法
2018/12/27 Python
对Python生成汉字字库文字,以及转换为文字图片的实例详解
2019/01/29 Python
用django设置session过期时间的方法解析
2019/08/05 Python
pandas实现将日期转换成timestamp
2019/12/07 Python
美国领先的礼品卡网站:GiftCards.com
2016/11/02 全球购物
一个J2EE项目团队的主要人员组成是什么
2012/06/04 面试题
信息管理专业学生自荐信格式
2013/09/22 职场文书
会议接待欢迎词
2014/01/12 职场文书
运动会表扬稿大全
2014/01/16 职场文书
销售会计岗位职责
2014/03/15 职场文书
防邪知识进家庭活动方案
2014/08/26 职场文书
党的群众路线教育实践活动实施方案
2014/10/31 职场文书
领导新年致辞2016
2015/07/29 职场文书
Vue + iView实现Excel上传功能的完整代码
2021/06/22 Vue.js
nginx中封禁ip和允许内网ip访问的实现示例
2022/03/17 Servers