基本实现了刮开图层,但是存在一个小问题,就是当用户滑动特别快时,会出现一些断点,当然也可以忽略,不过我们准备提供一下解决方案:
产生原因:由于鼠标移动速度过快,产生的断点;解决方案:将mousemove中两次的鼠标左边,进行拆分成多个断点坐标:
如上图,把两点之间进行连线,根据斜率,然后分成多个小段,分别获得线段上的坐标(有四种可能,有兴趣可以画画图,计算下,代码如下):
var k; if (p.x > this.startPoint.x) { k = (p.y - this.startPoint.y) / (p.x - this.startPoint.x); for (var i = this.startPoint.x; i < p.x; i += 5) { this.frontCanvas.clearRect({x: i, y: (this.startPoint.y + (i - this.startPoint.x) * k)}); } } else { k = (p.y - this.startPoint.y) / (p.x - this.startPoint.x); for (var i = this.startPoint.x; i > p.x; i -= 5) { this.frontCanvas.clearRect({x: i, y: (this.startPoint.y + ( i - this.startPoint.x ) * k)}); } } this.startPoint = p;
4、最后贴一下完整的GuaGuaLe.js
/** * Created with JetBrains WebStorm. * User: zhy * Date: 14-6-24 * Time: 上午11:36 * To change this template use File | Settings | File Templates. */ function GuaGuaLe(idFront, idBack) { this.$eleBack = $("#" + idBack); this.$eleFront = $("#" + idFront); this.frontCanvas = new Canvas2D(this.$eleFront); this.backCanvas = new Canvas2D(this.$eleBack); this.isStart = false; } GuaGuaLe.prototype = { constructor: GuaGuaLe, /** * 将用户的传入的参数和默认参数做合并 * @param desAttr * @returns {{frontFillColor: string, backFillColor: string, backFontColor: string, backFontSize: number, msg: string}} */ mergeAttr: function (desAttr) { var defaultAttr = { frontFillColor: "silver", backFillColor: "gold", backFontColor: "red", backFontSize: 24, msg: "谢谢惠顾" }; for (var p in desAttr) { defaultAttr[p] = desAttr[p]; } return defaultAttr; }, init: function (desAttr) { var attr = this.mergeAttr(desAttr); //初始化canvas this.backCanvas.penColor(attr.backFillColor); this.backCanvas.fontSize(attr.backFontSize); this.backCanvas.drawRect({x: 0, y: 0}, {x: this.backCanvas.width(), y: this.backCanvas.height()}, true); this.backCanvas.penColor(attr.backFontColor); this.backCanvas.drawTextInCenter(attr.msg, true); //初始化canvas this.frontCanvas.penColor(attr.frontFillColor); this.frontCanvas.drawRect({x: 0, y: 0}, {x: this.frontCanvas.width(), y: this.frontCanvas.height()}, true); var _this = this; //设置事件 this.$eleFront.mousedown(function (event) { _this.mouseDown(event); }).mousemove(function (event) { _this.mouseMove(event); }).mouseup(function (event) { _this.mouseUp(event); }); }, mouseDown: function (event) { this.isStart = true; this.startPoint = this.frontCanvas.getCanvasPoint(event.pageX, event.pageY); }, mouseMove: function (event) { if (!this.isStart)return; var p = this.frontCanvas.getCanvasPoint(event.pageX, event.pageY); this.frontCanvas.clearRect(p); }, mouseUp: function (event) { this.isStart = false; } };
源码点击下载:demo
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。