JAVASCRIPT+HTML5 Canvas Draw a turntable draw _javascript tips

Source: Internet
Author: User

Before the project, there is a need to draw turntable function. The project has been completed for some time, there is no serious bug, so now carry out to share with you.

Functional Requirements
1, turntable to beautiful, smooth rotation effect.
2, the turntable needs to display the prize picture, and the prize is backstage to read the photos and the name.
3, the rotation of the animation should have a corresponding prompt.
4, the acquisition of the prize specific algorithm in the database operation, the front-end only provide the final effect of the show.

Knowledge points
1, a reference to a JQ plug-in: awardrotate, used to achieve more intelligent rotation (plugin download: http://www.jqcool.net/jquery-jqueryrotate.html).
2, using the canvas tag and the corresponding HTML5 API to operate. (Canvas Chinese manual can view http://javascript.ruanyifeng.com/htmlapi/canvas.html

Body
refer to the large 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:[],//Large turntable prize name
 lucky:[],//Prize content
 colors:[],//large turntable prize block corresponding background color
 Goodsimgarr: [],//Prize picture page label
 outsideradius:175,//the radius of the outer circle of the large turntable
 textradius:140,//the distance from the center distance of the prize position
 insideradius:65,// The radius of the inner circle of the large turntable
 startangle:0,//start angle
 brotate:false//false: stop; ture: Rotate
 };

From the parameters, we need to obtain the corresponding prize name from the service side, the prize content, the prize picture page labels and other information, and then to the large turntable to render.
So our first step is to send a request to the server to get the corresponding prize information, and to traverse to the array parameters needed to generate the large 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 prize I got. JSON data:

[
 {
 "data0": "First Prize",
 "data1": "iphone6s",
 "data2": "0",
 "data3": "0",
 "data4": " 201510161406303384.png ",
 " Data5 ":" XXXX Network Technology ",
 " data6 ":" Zhejiang province Quzhou Kecheng District xxxxx ",
 " Data7 ":" 0570-xxxxxx
 " },......
 ]

Because the customer requests the prize not "thanks participates", therefore the lowest prize also is "the winning prize", therefore after traversing the prize, inserts regarding "The winning prize" The rendering description can:

Turnplate.goodsimgArr.push ('.. /images/hongbao.png ')
 Turnplate.restaraunts.push ("Winning award");
 Turnplate.colors.push ("#5fcbd4");
 After all elements of the page are loaded, the Drawroulettewheel () method is performed to render the turntable
 preloadimages (Turnplate.goodsimgarr). Done (function (images) {
 Drawroulettewheel ();
 });

Because the picture load takes time, and the use of canvas copy pictures need to be completed before painting, so I used the preloadimages, so that all the pictures of the prizes loaded after the large turntable rendering work:

To the trophy picture preload
 function preloadimages (arr) {
 var newimages =[], loadedimages =0
 var postaction =function () {}// Added here is a postaction function
 var arr = (typeof arr!= "Object")? [ ARR]: arr
 function Imageloadpost () {
 loadedimages++
 if (loadedimages = = arr.length) {
 postaction ( Newimages)//loading complete with We call the Postaction function and pass the newimages array as arguments in
 } 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 of returning a blank object here
 done:function (f) {
 postaction = f | | postaction
 }
 }}

To draw the dial code:

function Drawroulettewheel () {var canvas = document.getElementById ("Wheelcanvas");
 if (canvas.getcontext) {//According to the number of prizes calculate the circumference angle var arc =math.pi/(TURNPLATE.RESTARAUNTS.LENGTH/2);
 var ctx = Canvas.getcontext ("2d");
 Clears a rectangular ctx.clearrect (0,0,422,422) within a given rectangle;
 Strokestyle property to set or return the color, gradient, or pattern used for strokes Ctx.strokestyle = "Rgba (0,0,0,0)";
 The Font property sets or returns the current font properties of the text content on the canvas Ctx.font = ' bold 18px Microsoft Yahei ';
 Rc
 Draws a fan-filled color ctx.fillstyle = turnplate.colors[i] According to the prize parameters;
 Start Drawing fan Ctx.beginpath (); Arc (x,y,r, start angle, end angle, drawing direction) method to create Arcs/curves (for creating a circle or part of a circle)//drawing a great circle Ctx.arc (212,212, Turnplate.outsideradius, angle, angle + arc,
 FALSE);
 Draw small round Ctx.arc (212,212, Turnplate.insideradius, Angle + arc, angle,true);
 Ctx.stroke ();
 Ctx.fill ();
 Lock the canvas (in order to save the previous canvas state) Ctx.save ();
 ----Draw the prize start----//prize default font Color Ctx.fillstyle = "#fff";
 var text = Turnplate.restaraunts[i]; var lukyname = Turnplate.lucky[i];
 var line_height = 17; The Translate method remap (0,0) position on the canvas ctx.translate (212+math.cos (angle + arc/2) * Turnplate.textradius,212+math.sin (angle +
 ARC/2) * Turnplate.textradius);
 The Rotate method rotates the current drawing ctx.rotate (angle + ARC/2+MATH.PI/2);
 Draw the prize picture var img =newimage ();
 IMG.SRC = Turnplate.goodsimgarr[i];
 Ctx.drawimage (img,-17,35);
 Because the design of the turntable color block is staggered, so this can achieve adjacent prize area font Color different if (i%2==0) {Ctx.fillstyle = "#f7452f";
 ///Draw the font in the corresponding coordinate Ctx.filltext (Text,-ctx.measuretext (text). width/2,0);
 Set Font Ctx.font = ' 14px Microsoft yahei ';
 Draw the prize name if (text!= "winning award") {Ctx.filltext (Lukyname,-ctx.measuretext (lukyname). width/2,25);
 }else{Ctx.filltext ("Excellent wheat Coin",-ctx.measuretext ("Excellent wheat Coin"). width/2,25);
 ///Ctx.restore () before returning the current canvas (insert) to the previous save () state;
 Ctx.save ();
 ----Draw the prize end----}}

Each step basically has the annotation, for canvas method has not understood can Baidu, or inquires me above to share the Chinese handbook.
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>

Effect Chart:

Click the event execution 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 did not log in or user data abnormal, 1092 users residual points, 1093 did not win
 Hideinput (" Code ", Data.code)
 if (data.code.toString () =" 1090 ") {
 Iosalert (" System configuration Error ")
 }elseif (data.code.toString () = = "1091") {
 Iosalert ("User is not logged in or user Data exception")
 }elseif (data.code.toString () = "1092") {
 Iosalert ("Insufficient user remaining points")
 }elseif (data.code.toString () = = "1094") {
 Iosalert ("More than the daily draw count")
 }
 else{
 var upoint =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 obtained," + Turnplate.restaraunts[item]);
 }
 else{
 rotatefn (0, "Congratulations for winning the prize!") ");
 }
 }
 })
 });

The above code implements the basic logic, and requires a rotating turntable to respond to the results of the service end:

Rotating Turntable Item: prize position; TXT: hint language;
 var rotatefn =function (item, TXT) {
 //To calculate the corresponding radians
 var angles = Item * (360/TURNPLATE.RESTARAUNTS.LENGTH) based on the prize number passed in (360/(Turnplate.restaraunts.length *2));
 if (angles <270) {
 angles =270-angles;
 } else{
 angles =360-angles +270;
 }
 Force stop rotation of the turntable
 $ (' #wheelcanvas '). Stoprotate ();
 Call the rotation method, set the required parameters for rotation and the callback function
 $ (' #wheelcanvas '). Rotate ({
 ///Starting angle
 angle:0,
 //rotation angle +1800 is for a few more laps
 . Animateto:angles +1800,
 duration:8000,
 callback:function () {
 iossuccess (TXT);
 Turnplate.brotate =!turnplate.brotate;
 if ($ ("#code"). Val ()!= "1093") {
 delayload (gethttpprefix + "graphicdetails.html?lukyid=" + $ ("#code"). Val ())
 }
 }
 });
 };

All right, the main functional code has been shared, and some tools do not understand, you can leave a message I will add.
Summary
Canvas is HTML5 a very powerful trump card, can achieve a lot of gorgeous effect, hope this article can help some are learning to use canvas friends.

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.