Javascrip + HTML5 Canvas draw turntable lottery, javascriphtml5

Source: Internet
Author: User

Javascrip + HTML5 Canvas draw turntable lottery, javascriphtml5

In previous projects, the lottery turntable function is required. The project has been completed for a while, and there are no major bugs, so I will share it with you now.

Functional requirements
1. Make the turntable beautiful and smooth.
2. A picture of the prize must be displayed on the turntable, and the prize is the photo and name read from the background.
3. After the animation is completed, a prompt should be displayed.
4. The algorithm used to obtain the prize is operated on the database. The front-end only displays the final result.

Knowledge points
1. referenced a jq plug-in: awardRotate, used to achieve more intelligent rotation (plug-in download: http://www.jqcool.net/jquery-jqueryrotate.html ).
2. Use the canvas label and the corresponding html5 api for operations. (Canvas Chinese manual can view http://javascript.ruanyifeng.com/htmlapi/canvas.html

Body
Reference big turntable Style

.lunck_draw_wrap{display:block;width:95%;margin-right:auto;} .lunck_draw_wrap .turnplate{display:block;width:106%; position:relative;}  .lunck_draw_wrap .turnplate canvas.item{left:1px;  position: relative;  top:9px;  width:100%;}  .lunck_draw_wrap .turnplate img.pointer{ height:37.5%;  left:34.6%;  position: absolute;  top:30%;  width:31.5%;}

Parameters required for the turntable plug-in:

Var turnplate = {restaraunts: [], // grand turntable prize name lucky: [], // prize content colors: [], // the background color goodsimgArr of the Grand turntable prize block: [], // prize image page tag outsideRadius: 175, // radius of the outer circle of the big turntable textRadius: 140, // distance from the center of the Grand turntable prize position to insideRadius: 65, // The radius of the incircle of the big turntable startAngle: 0, // start angle bRotate: false // false: Stop; ture: Rotate };

According to the parameters, we need to obtain the corresponding prize name, prize content, prize image page tag and other information from the server, and then render the big turntable.
Therefore, our first step is to send a request to the server to obtain the corresponding prize information and traverse it to the array parameters required to generate the big turntable:

$.each(data.list,function(key, value){ turnplate.restaraunts.push(value.data0); turnplate.lucky.push(value.data1); turnplate.goodsimgArr.push(getLuckyImg + value.data4); if(key %2==0) turnplate.colors.push("#fff"); else turnplate.colors.push("#5fcbd4"); }) 

Data. list is the json data of the prize I have obtained:

[{"Data0": "First Prize", "data1": "iphone6s", "data2": "0", "data3": "0", "data4 ": "201510161406303384.png"," data5 ":" XXXX Network Technology "," data6 ":" XXXXX, kecheng district, Quzhou city, Zhejiang Province "," data7 ":" 0570-XXXXXX "},...]

Because the customer requested that the prize not be "thank you for participation", the lowest prize is also "Winner", so after traversing the prize, insert the rendering description about "Winner:

Turnplate. goodsimgArr. push ('.. /images/hongbao.png ') turnplate. restaraunts. push ("Winner"); turnplate. colors. push ("#5fcbd4"); // after all the elements on the page are loaded, execute the drawRouletteWheel () method to render the turntable preloadimages (turnplate. goodsimgArr ). done (function (images) {drawRouletteWheel ();});

Because it takes time to attach images, while copying images using canvas requires that the images be loaded before they can be drawn. Therefore, I used preloadimages to make all the prize images ready for rendering on the big turntable:

// Function preloadimages (arr) {var newimages = [], loadedimages = 0 var postaction = function () {} // A postaction function var arr = (typeof arr! is added here! = "Object ")? [Arr]: arr function imageloadpost () {loadedimages ++ if (loadedimages = arr. length) {postaction (newimages) // after loading is complete, call the postaction function and pass the newimages array as a parameter.} for (var I = 0; I <arr. length; I ++) {newimages [I] = newImage () newimages [I]. src = arr [I] newimages [I]. onload = function () {imageloadpost ()} newimages [I]. onerror = function () {imageloadpost ()} return {// The done method for returning a blank object done: function (f) {postaction = f | postaction }}}

Code for drawing the turntable:

Function drawRouletteWheel () {var canvas = document. getElementById ("wheelcanvas"); if (canvas. getContext) {// calculate the circumference angle var arc = Math based on the number of prizes. PI/(turnplate. restaraunts. length/2); var ctx = canvas. getContext ("2d"); // clear a rectangle ctx in the given rectangle. clearRect (422,422,); // set the strokeStyle attribute or return the color, gradient, or pattern ctx used for strokes. strokeStyle = "rgba (,)"; // set the font attribute or return the current font attribute ctx of the text content on the canvas. font = 'bold 18px Microsoft yahei'; for (var I = 0; I <turnplate. restaraunts. length; I ++) {// calculates the slice starting radian var angle = turnplate based on the current prize index. startAngle + I * arc; // draw a sector fill color ctx Based on the prize parameters. fillStyle = turnplate. colors [I]; // start to draw a sector ctx. beginPath (); // arc (x, y, r, start angle, end angle, draw direction) method to create an arc/curve (used to create a circle or a part of a circle) // draw a large circle ctx. arc( 212,212, turnplate. outsideRadius, angle, angle + arc, false); // draw a small circle ctx. arc( 212,212, turnplate. insideRadius, angle + arc, angle, true); ctx. stroke (); Ctx. fill (); // lock the canvas (to save the previous canvas status) ctx. save (); // ---- draw the prize start ---- // default font color of the prize ctx. fillStyle = "# fff"; var text = turnplate. restaraunts [I]; var lukyname = turnplate. lucky [I]; var line_height = 17; // The translate method remaps the (0, 0) Position ctx on the canvas. translate (212 + Math. cos (angle + arc/2) * turnplate. textRadius, 212 + Math. sin (angle + arc/2) * turnplate. textRadius); // The rotate method rotates the current plot ctx. rotate (angle + arc/2 + Math. PI/2); // draw a prize chart Slice var img = newImage (); img. src = turnplate. goodsimgArr [I]; ctx. drawImage (img,-); // because the color block of the designed turntable is staggered, the font color of the adjacent prize area can be different if (I % 2 = 0) {ctx. fillStyle = "# f7452f";} // draw the font in the corresponding coordinates ctx. fillText (text,-ctx. measureText (text ). width/2, 0); // set the font ctx. font = '14px Microsoft yahei'; // draw the prize name if (text! = "Winner") {ctx. fillText (lukyname,-ctx. measureText (lukyname ). width/2, 25);} else {ctx. fillText ("youmai coin",-ctx. measureText ("youmai coin "). width/);} // return (insert) The current canvas before the previous save () status ctx. restore (); ctx. save (); // ---- draw prize end ----}}}

Each step is basically annotated. If you do not understand the canvas method, you can use Baidu or query the Chinese manual I shared above.
The html code is:

<divclass="lunck_draw_wrap"> <divclass="turnplate"style=" background-size:100%100%;"> <canvasclass="item"id="wheelcanvas"width="422px"height="422px"></canvas>   </div> </div>

:

Click the event to execute the Code:

$ ('. Lunck_draw_wrap'). delegate ("img. pointer", "click", function () {if (turnplate. bRotate) return; turnplate. bRotate =! Turnplate. bRotate; $. getJSON (".. /AJAX/lottery. ashx "," ", function (data) {// 1090 system configuration error, 1091 users not logged in or user data exception, 1092 users have insufficient credits, 1093 hideInput ("code", data. code) if (data. code. toString () = "1090") {iosalert ("system configuration error")} elseif (data. code. toString () = "1091") {iosalert ("user not logged in or User data Exception")} elseif (data. code. toString () = "1092") {iosalert ("insufficient user points remaining")} elseif (data. code. toString () = "1094") {iosalert ("more than the number of Lottery draws per day")} else {var up Oint = 0; upoint = parseInt ($ ("# uPoint" ).html ()-parseInt ($ ("# sPoint" ).html ()); $ ("# uPoint" ).html (upoint); if (data. isWin = 'true') {item = getArrayIndex (turnplate. restaraunts, data. name); rotateFn (item + 1, "congratulations," + turnplate. restaraunts [item]);} else {rotateFn (0, "Congratulations! ");}}})});

The above code implements the basic logic, and also requires a method to rotate the turntable to respond to the results uploaded by the server:

// Rotating turntable item: prize location; txt: prompt; var rotateFn = function (item, txt) {// calculate the corresponding radian var angles = item * (360/turnplate. restaraunts. length)-(360/(turnplate. restaraunts. length * 2); if (angles <270) {angles = 270-angles;} else {angles = 360-angles + 270 ;} // force stop the rotation of the turntable $ ('# wheelcanvas '). stopRotate (); // call the rotation method to set the required parameters and callback functions for rotation $ ('# wheelcanvas '). rotate ({// start angle: 0, // rotation angle + 1800 is used to turn a few more laps of animateTo: angles + 1800, duration: 8000, callback: function () {iosSuccess (txt); turnplate. bRotate =! Turnplate. bRotate; if ($ ("# code"). val ()! = "1093") {delayLoad (getHttpPrefix + "graphicdetails.html? Lukyid = "+ $ (" # code "). val ())}}});};

Well, the main function code has been shared, and some tools and methods are not understood. I will add them to the comment.
Summary
Canvas is a powerful trump card of html5 and can achieve many brilliant results. I hope this article will help some friends who are learning to use canvas.

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.