Canvas simulation to achieve electronic lottery scraping music

Source: Internet
Author: User
Today to bring you a scratch of the small example ~ based on HTML5 canvas, interested can be changed to Android version, or other ~

Put a picture of me in 500w, how to do, How to flowers ~

OK, here's how it starts:

1, scraping award area two canvas, one is front, a back, front cover the following canvas.

2, the canvas is filled by default a rectangle, the following canvas is obscured, and then listen to the mouse event, according to MouseMove X, y coordinates, to wipe out the rectangular area of the front canvas, and then display the following canvas.

Very simple to ~ hehe ~

1. html File content:

<! DOCTYPE html> 

2, first I used a previously written canvas helper class, left to use some of the methods today:

/** * Created with JetBrains webstorm. * User:zhy * date:13-12-17 * Time: PM 9:42 * To change this template with File | Settings |  File Templates.          */function Canvas2d ($canvas) {var context = $canvas [0].getcontext ("2d"), width = $canvas [0].width,          Height = $canvas [0].height, Pageoffset = $canvas. Offset ();      Context.font = "24px Verdana, Geneva, Sans-serif";          Context.textbaseline = "Top"; /** * Draw Rectangle * @param start * @param end * @param isfill */this.drawrect = function (Start, E          nd, Isfill) {var w = end.x-start.x, h = end.y-start.y;          if (Isfill) {context.fillrect (Start.x, Start.y, W, h);          } else {context.strokerect (start.x, Start.y, W, h);        }      }; /** * Based on the written text, the upper-left coordinate of the text in the center of the canvas where it is written @param text * @returns {{x:number, y:number}} */Thi S.caculatetextcenterpos = function (text) {var metrics = context.measuretext (text);  Console.log (metrics);          Context.font = fontSize + "px Verdana, Geneva, Sans-serif";          var textWidth = metrics.width;            var textHeight = parseint (Context.font);      return {X:WIDTH/2-TEXTWIDTH/2, Y:HEIGHT/2-TEXTHEIGHT/2};      } this.width = function () {return width;      } this.height = function () {return height;      } This.resetoffset = function () {Pageoffset = $canvas. Offset (); /** * When the screen size changes, recalculate offset */$ (window). Resize (function () {Pageoffset = $canvas. Offs      ET ();        });      /** * Converts the left side of the page to the coordinates in the canvas * @param pageX * @param pagey * @returns {{x:number, y:number}} */ This.getcanvaspoint = function (PageX, pagey) {return{x:pagex-pageoffset.left,             Y:pagey-pageoffset.top}}/** * Clear area, this user mouse scratches the scratch coating * @param start * @retu          RNS {*} */this.clearrect = function (start) {Context.clearrect (Start.x, Start.y, 10, 10);      return this;        };       /** * Draws text to the middle of the canvas * @param text * @param fill */this.drawtextincenter = function (text, fill)          {var point = This.caculatetextcenterpos (text);          if (fill) {Context.filltext (text, point.x, POINT.Y);          } else {context.stroketext (text, point.x, POINT.Y);      }      };          /** * Set Brush width * @param newwidth * @returns {*} */this.penwidth = function (newwidth) {              if (arguments.length) {context.linewidth = Newwidth;          return this;      } return context.linewidth;        }; /** * Set Brush color * @param newcolor * @returns {*} */This.pencolor = function (Newcolor) {if (arguments.length) {              Context.strokestyle = Newcolor;              Context.fillstyle = Newcolor;          return this;      } return Context.strokestyle;        };          /** * Set Font size * @param fontSize * @returns {*} */this.fontsize = function (fontSize) {                if (arguments.length) {Context.font = fontSize + "px Verdana, Geneva, Sans-serif";          return this;      } return context.fontsize; }      }

This class also on the canvas object is a simple package, set parameters, draw graphics what, relatively simple, we can improve the next class ~

3, Guaguale.js

/** * Created with JetBrains webstorm. * User:zhy * date:14-6-24 * Time: Morning 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,/** * Merges the user's incoming parameters and default parameters * @param desattr * @re      Turns {{frontfillcolor:string, backfillcolor:string, backfontcolor:string, Backfontsize:number, msg:string}} */              Mergeattr:function (desattr) {var defaultattr = {frontfillcolor: "Silver",          Backfillcolor: "Gold", Backfontcolor: "Red", Backfontsize:24, msg: "Thank you for your patronage"          };          For (var p in desattr) {defaultattr[p] = desattr[p]; }            return defaultattr;            }, Init:function (desattr) {var attr = this.mergeattr (desattr);          Initialize 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);          Initialize 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;          Set event 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; }  };

The user passes in the ID of the two canvas, then generates an object, initializes the operation, and sets the event. Of course. Also provides user settings optional parameters, various colors, has been scraped after the display of information, etc., through

{            frontfillcolor: "Silver",            backfillcolor: "Gold",            backfontcolor: "Red",            backfontsize:24,            msg : "Thank you for your patronage"        };

Passed to the Init method for Setup.

OK, and then basically finished, test it out:

The basic implementation of the scratch layer, but there is a small problem, that is, when the user sliding particularly fast, there will be some breakpoints, of course, can be ignored, but we are ready to provide a solution:

Cause: Due to the mouse movement speed too fast, the resulting breakpoint; solution: MouseMove two times in the left side of the mouse, split into multiple breakpoint coordinates:

For example, the connection between two points, according to the slope, and then divided into a number of small segments, respectively, to obtain the coordinates on the line segment (there are four possibilities, interested in drawing, calculation, code as follows):

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, finally paste the complete guaguale.js

/** * Created with JetBrains webstorm. * User:zhy * date:14-6-24 * Time: Morning 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,/** * Merges the user's incoming parameters and default parameters * @param desattr * @re      Turns {{frontfillcolor:string, backfillcolor:string, backfontcolor:string, Backfontsize:number, msg:string}} */              Mergeattr:function (desattr) {var defaultattr = {frontfillcolor: "Silver",          Backfillcolor: "Gold", Backfontcolor: "Red", Backfontsize:24, msg: "Thank you for your patronage"          };          For (var p in desattr) {defaultattr[p] = desattr[p]; }            return defaultattr;            }, Init:function (desattr) {var attr = this.mergeattr (desattr);          Initialize 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);          Initialize 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;          Set event 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; }  };

The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support topic.alibabacloud.com.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.