js canvas实现橡皮擦效果

本文实例为大家分享了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是库函数文件,可网上自行查找

出来的效果如图

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

(0)

相关推荐

  • cocos2dx+lua实现橡皮擦功能

    游戏中刮刮乐是怎么实现的?做了一个小例子看了一下. 实现原理:随着触摸点的移动,通过setBlendFunc函数设置部分区域的颜色混合(将上层图片透明度为0,底层我们想要的图片就显示出来) --橡皮擦功能测试 local function initInfo() local scene = CCScene:create() local layer = CCLayer:create() scene:addChild(layer) --擦除后要显示的图片 local tupian = CCSprite

  • cocos2dx实现橡皮擦效果以及判断是否擦除完毕

    本文实例为大家分享了cocos2dx实现橡皮擦效果,以及判断是否擦除完毕,供大家参考,具体内容如下 首先修改HelloWorld.h文件 #ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" #include "cocos-ext.h" USING_NS_CC_EXT; USING_NS_CC; class HelloWorld : public coco

  • 基于canvas剪辑区域功能实现橡皮擦效果

    效果如图 这是基础结构 没什么好说的 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-C

  • js canvas实现橡皮擦效果

    本文实例为大家分享了canvas实现橡皮擦效果的具体代码,供大家参考,具体内容如下 html部分 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html" charset="utf-8" /> <meta name="viewport" content="in

  • 原生js+canvas实现下雪效果

    本文实例为大家分享了js+canvas实现下雪效果的具体代码,供大家参考,具体内容如下 效果展示: 源码展示: <!doctype html> <html> <head> <meta charset="utf-8"> <title>canvas下雪效果(原生js)</title> <style> * { margin: 0; padding: 0 } html, body { width: 100%;

  • js+canvas实现转盘效果(两个版本)

    本文实例为大家分享了js+canvas实现转盘效果的具体代码,供大家参考,具体内容如下 用到了canvas的绘制,旋转,重绘操作,定时器,文本,平移,线条,圆,清理画布等等: 版本一 不可以点击,刷新旋转 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>转盘抽奖</title> <style type="text/css&quo

  • js canvas实现擦除效果示例代码

    关于canvas的定义: HTML5 的 canvas 元素使用 JavaScript 在网页上绘制图像. 画布是一个矩形区域,您可以控制其每一像素. canvas 拥有多种绘制路径.矩形.圆形.字符以及添加图像的方法. html代码: <div class="container"> <canvas id="canvas" width="200" height="50"></canvas>

  • JS+Canvas绘制时钟效果

    本文实例为大家分享了使用canvas绘制时钟的具体代码,供大家参考,具体内容如下 1. clock.html    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Description" content=""> <title>canvas时钟</t

  • js+canvas实现代码雨效果

    本文实例为大家分享了js+canvas代码雨效果的具体代码,供大家参考,具体内容如下 代码: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> *{ margin: 0px; padding: 0px; } html,body{ height:

  • JS+canvas绘制的动态机械表动画效果

    本文实例讲述了JS+canvas绘制的动态机械表动画效果.分享给大家供大家参考,具体如下: 先来看看运行效果: 完整实例代码: <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>www.jb51.net canvas时钟</title> <style> canvas { border: 1px

  • JS+canvas画布实现炫酷的旋转星空效果示例

    本文实例讲述了JS+canvas画布实现炫酷的旋转星空效果.分享给大家供大家参考,具体如下: canvas是html5的新标签,其画布功能尤为强大.当然了canvas在IE10以下浏览器是不兼容的,所以呢为了特效肯定是牺牲一定的兼容性.这里呢,分享一个基于canvas开发的浩瀚星河插件,其实这个源代码是网上下载的,我把它整合了一下,重新封装一些参数提供更多的可改项. 首先引入两个javascript脚本,一个是jquery插件,另一个是封装好的cosmos_canvas.js <script s

  • js canvas实现写字动画效果

    本文实例为大家分享了js canvas实现写字动画效果展示的具体代码,供大家参考,具体内容如下 页面html: <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>学写一个字</title> <script src="jquery-2.1.3.min.js" type="t

随机推荐