欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js canvas实现橡皮擦效果

程序员文章站 2022-03-24 13:02:43
本文实例为大家分享了canvas实现橡皮擦效果的具体代码,供大家参考,具体内容如下 html部分

本文实例为大家分享了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实现橡皮擦效果

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