大转盘抽奖

这周做了2个大转盘抽奖,一个使用了jQueryRotate.2.2.js插件,兼容到IE6,另外一个利用css3自己尝试写的

1、插件jQueryRotate.2.2.js(兼容基本浏览器,兼容到IE6

效果查看:

此插件必须事先引入jquery插件,PC端推荐

JS插件代码:

// VERSION: 2.2 LAST UPDATE: 13.03.2012
/*
 * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 *
 * Made by Wilq32, [email protected], Wroclaw, Poland, 01.2009
 * Website: http://code.google.com/p/jqueryrotate/
 */

// Documentation removed from script file (was kinda useless and outdated)

(function($) {
var supportedCSS,styles=document.getElementsByTagName("head")[0].style,toCheck="transformProperty WebkitTransform OTransform msTransform MozTransform".split(" ");
for (var a=0;a<toCheck.length;a++) if (styles[toCheck[a]] !== undefined) supportedCSS = toCheck[a];
// Bad eval to preven google closure to remove it from code o_O
// After compresion replace it back to var IE = ‘v‘ == ‘\v‘
var IE = eval(‘"v"=="\v"‘);

jQuery.fn.extend({
    rotate:function(parameters)
    {
        if (this.length===0||typeof parameters=="undefined") return;
            if (typeof parameters=="number") parameters={angle:parameters};
        var returned=[];
        for (var i=0,i0=this.length;i<i0;i++)
            {
                var element=this.get(i);
                if (!element.Wilq32 || !element.Wilq32.PhotoEffect) {

                    var paramClone = $.extend(true, {}, parameters);
                    var newRotObject = new Wilq32.PhotoEffect(element,paramClone)._rootObj;

                    returned.push($(newRotObject));
                }
                else {
                    element.Wilq32.PhotoEffect._handleRotation(parameters);
                }
            }
            return returned;
    },
    getRotateAngle: function(){
        var ret = [];
        for (var i=0,i0=this.length;i<i0;i++)
            {
                var element=this.get(i);
                if (element.Wilq32 && element.Wilq32.PhotoEffect) {
                    ret[i] = element.Wilq32.PhotoEffect._angle;
                }
            }
            return ret;
    },
    stopRotate: function(){
        for (var i=0,i0=this.length;i<i0;i++)
            {
                var element=this.get(i);
                if (element.Wilq32 && element.Wilq32.PhotoEffect) {
                    clearTimeout(element.Wilq32.PhotoEffect._timer);
                }
            }
    }
});

// Library agnostic interface

Wilq32=window.Wilq32||{};
Wilq32.PhotoEffect=(function(){

    if (supportedCSS) {
        return function(img,parameters){
            img.Wilq32 = {
                PhotoEffect: this
            };

            this._img = this._rootObj = this._eventObj = img;
            this._handleRotation(parameters);
        }
    } else {
        return function(img,parameters) {
            // Make sure that class and id are also copied - just in case you would like to refeer to an newly created object
            this._img = img;

            this._rootObj=document.createElement(‘span‘);
            this._rootObj.style.display="inline-block";
            this._rootObj.Wilq32 =
                {
                    PhotoEffect: this
                };
            img.parentNode.insertBefore(this._rootObj,img);

            if (img.complete) {
                this._Loader(parameters);
            } else {
                var self=this;
                // TODO: Remove jQuery dependency
                jQuery(this._img).bind("load", function()
                {
                    self._Loader(parameters);
                });
            }
        }
    }
})();

Wilq32.PhotoEffect.prototype={
    _setupParameters : function (parameters){
        this._parameters = this._parameters || {};
        if (typeof this._angle !== "number") this._angle = 0 ;
        if (typeof parameters.angle==="number") this._angle = parameters.angle;
        this._parameters.animateTo = (typeof parameters.animateTo==="number") ? (parameters.animateTo) : (this._angle); 

        this._parameters.step = parameters.step || this._parameters.step || null;
        this._parameters.easing = parameters.easing || this._parameters.easing || function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }
        this._parameters.duration = parameters.duration || this._parameters.duration || 1000;
        this._parameters.callback = parameters.callback || this._parameters.callback || function(){};
        if (parameters.bind && parameters.bind != this._parameters.bind) this._BindEvents(parameters.bind);
    },
    _handleRotation : function(parameters){
          this._setupParameters(parameters);
          if (this._angle==this._parameters.animateTo) {
              this._rotate(this._angle);
          }
          else {
              this._animateStart();
          }
    },

    _BindEvents:function(events){
        if (events && this._eventObj)
        {
            // Unbinding previous Events
            if (this._parameters.bind){
                var oldEvents = this._parameters.bind;
                for (var a in oldEvents) if (oldEvents.hasOwnProperty(a))
                        // TODO: Remove jQuery dependency
                        jQuery(this._eventObj).unbind(a,oldEvents[a]);
            }

            this._parameters.bind = events;
            for (var a in events) if (events.hasOwnProperty(a))
                // TODO: Remove jQuery dependency
                    jQuery(this._eventObj).bind(a,events[a]);
        }
    },

    _Loader:(function()
    {
        if (IE)
        return function(parameters)
        {
            var width=this._img.width;
            var height=this._img.height;
            this._img.parentNode.removeChild(this._img);

            this._vimage = this.createVMLNode(‘image‘);
            this._vimage.src=this._img.src;
            this._vimage.style.height=height+"px";
            this._vimage.style.width=width+"px";
            this._vimage.style.position="absolute"; // FIXES IE PROBLEM - its only rendered if its on absolute position!
            this._vimage.style.top = "0px";
            this._vimage.style.left = "0px";

            /* Group minifying a small 1px precision problem when rotating object */
            this._container =  this.createVMLNode(‘group‘);
            this._container.style.width=width;
            this._container.style.height=height;
            this._container.style.position="absolute";
            this._container.setAttribute(‘coordsize‘,width-1+‘,‘+(height-1)); // This -1, -1 trying to fix ugly problem with small displacement on IE
            this._container.appendChild(this._vimage);

            this._rootObj.appendChild(this._container);
            this._rootObj.style.position="relative"; // FIXES IE PROBLEM
            this._rootObj.style.width=width+"px";
            this._rootObj.style.height=height+"px";
            this._rootObj.setAttribute(‘id‘,this._img.getAttribute(‘id‘));
            this._rootObj.className=this._img.className;
            this._eventObj = this._rootObj;
            this._handleRotation(parameters);
        }
        else
        return function (parameters)
        {
            this._rootObj.setAttribute(‘id‘,this._img.getAttribute(‘id‘));
            this._rootObj.className=this._img.className;

            this._width=this._img.width;
            this._height=this._img.height;
            this._widthHalf=this._width/2; // used for optimisation
            this._heightHalf=this._height/2;// used for optimisation

            var _widthMax=Math.sqrt((this._height)*(this._height) + (this._width) * (this._width));

            this._widthAdd = _widthMax - this._width;
            this._heightAdd = _widthMax - this._height;    // widthMax because maxWidth=maxHeight
            this._widthAddHalf=this._widthAdd/2; // used for optimisation
            this._heightAddHalf=this._heightAdd/2;// used for optimisation

            this._img.parentNode.removeChild(this._img);    

            this._aspectW = ((parseInt(this._img.style.width,10)) || this._width)/this._img.width;
            this._aspectH = ((parseInt(this._img.style.height,10)) || this._height)/this._img.height;

            this._canvas=document.createElement(‘canvas‘);
            this._canvas.setAttribute(‘width‘,this._width);
            this._canvas.style.position="relative";
            this._canvas.style.left = -this._widthAddHalf + "px";
            this._canvas.style.top = -this._heightAddHalf + "px";
            this._canvas.Wilq32 = this._rootObj.Wilq32;

            this._rootObj.appendChild(this._canvas);
            this._rootObj.style.width=this._width+"px";
            this._rootObj.style.height=this._height+"px";
            this._eventObj = this._canvas;

            this._cnv=this._canvas.getContext(‘2d‘);
            this._handleRotation(parameters);
        }
    })(),

    _animateStart:function()
    {
        if (this._timer) {
            clearTimeout(this._timer);
        }
        this._animateStartTime = +new Date;
        this._animateStartAngle = this._angle;
        this._animate();
    },
    _animate:function()
    {
         var actualTime = +new Date;
         var checkEnd = actualTime - this._animateStartTime > this._parameters.duration;

         // TODO: Bug for animatedGif for static rotation ? (to test)
         if (checkEnd && !this._parameters.animatedGif)
         {
             clearTimeout(this._timer);
         }
         else
         {
             if (this._canvas||this._vimage||this._img) {
                 var angle = this._parameters.easing(0, actualTime - this._animateStartTime, this._animateStartAngle, this._parameters.animateTo - this._animateStartAngle, this._parameters.duration);
                 this._rotate((~~(angle*10))/10);
             }
             if (this._parameters.step) {
                this._parameters.step(this._angle);
             }
             var self = this;
             this._timer = setTimeout(function()
                     {
                     self._animate.call(self);
                     }, 10);
         }

         // To fix Bug that prevents using recursive function in callback I moved this function to back
         if (this._parameters.callback && checkEnd){
             this._angle = this._parameters.animateTo;
             this._rotate(this._angle);
             this._parameters.callback.call(this._rootObj);
         }
     },

    _rotate : (function()
    {
        var rad = Math.PI/180;
        if (IE)
        return function(angle)
        {
            this._angle = angle;
            this._container.style.rotation=(angle%360)+"deg";
        }
        else if (supportedCSS)
        return function(angle){
            this._angle = angle;
            this._img.style[supportedCSS]="rotate("+(angle%360)+"deg)";
        }
        else
        return function(angle)
        {
            this._angle = angle;
            angle=(angle%360)* rad;
            // clear canvas
            this._canvas.width = this._width+this._widthAdd;
            this._canvas.height = this._height+this._heightAdd;

            // REMEMBER: all drawings are read from backwards.. so first function is translate, then rotate, then translate, translate..
            this._cnv.translate(this._widthAddHalf,this._heightAddHalf);    // at least center image on screen
            this._cnv.translate(this._widthHalf,this._heightHalf);            // we move image back to its orginal
            this._cnv.rotate(angle);                                        // rotate image
            this._cnv.translate(-this._widthHalf,-this._heightHalf);        // move image to its center, so we can rotate around its center
            this._cnv.scale(this._aspectW,this._aspectH); // SCALE - if needed ;)
            this._cnv.drawImage(this._img, 0, 0);                            // First - we draw image
        }

    })()
}

if (IE)
{
Wilq32.PhotoEffect.prototype.createVMLNode=(function(){
document.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)");
        try {
            !document.namespaces.rvml && document.namespaces.add("rvml", "urn:schemas-microsoft-com:vml");
            return function (tagName) {
                return document.createElement(‘<rvml:‘ + tagName + ‘ class="rvml">‘);
            };
        } catch (e) {
            return function (tagName) {
                return document.createElement(‘<‘ + tagName + ‘ xmlns="urn:schemas-microsoft.com:vml" class="rvml">‘);
            };
        }
})();
}

})(jQuery);

页面调用代码

//awards:奖项,angle:奖项对应的角度,text:提示文字

var rotateFunc = function(awards,angle,text){

$lotterywheel.stopRotate();

$lotterywheel.rotate({

angle:0,

duration: 5000, //转盘转动时间

animateTo: angle+1440, //angle是图片上各奖项对应的角度,1440是我要让指针旋转4圈。所以最后的结束的角度就是这样子^^

callback:function(){ //回掉函数

alert(text);

      flag = true;

}

});

};

在需要转盘旋转的地方调用函数

rotateFunc(awards,angle,text),比如

if(data==1){

rotateFunc(1,90,‘恭喜您抽中的一等奖‘)

}

if(data==2){

rotateFunc(2,180,‘恭喜您抽中的二等奖‘)

}

if(data==3){

rotateFunc(3,270,‘恭喜您抽中的三等奖‘)

}

判断获奖奖品时按照顺时间的角度计算

2、插件BigRotate.js(兼容高级浏览器,IE9以上)

此插件可基于Jquery,Zepto等插件,推荐在手机上使用

在需要转动的元素上要写上transition,比如

.lotteryBg{

transition: transform 2s;

-webkit-transition: -webkit-transform 2s;

-moz-transition: -moz-transform 2s;

-o-transition: -o-transform 2s;

}

在需要的地方// 调用抽奖插件,参数(转动的盘,几等奖,改奖品旋转角度,中奖之后执行的函数)

rotateFunc($lotterywheel,3,90,function(){alertFun("获得三等奖")});

/* 抽奖 */
var islogin = true;
    // 转盘转动完之后的事件
    function alertFun(text){
        alert(text);
        flag = true;
    }

    /* 抽奖按钮事件绑定 */
    var data = [1,2,3,0]; //返回的数组
    $lotteryArrow.on(‘click‘,function(){
        if(flag){
            console.log("开始抽奖");
            // 本地模拟随机生成奖品
            var n = data[Math.floor(Math.random()*data.length)];
            flag = false;
            // 调用抽奖插件,参数(转动的盘,几等奖,改奖品旋转角度,中奖之后执行的函数)
            if(n == 1){
                rotateFunc($lotterywheel,1,45,function(){alertFun("恭喜或得到一等奖")});
            } else if(n== 2){
                rotateFunc($lotterywheel,1,90,function(){alertFun("恭喜或得到二等奖")});
            } else if(n == 3){
                rotateFunc($lotterywheel,3,135,function(){alertFun("恭喜或得到三等奖")});
            }

        }
    })

默认转2圈后再到达中奖的位置,判断获奖奖品时按照逆时间的角度计算

附上JS插件代码:

/* ==========================================================
 * BigRotate.js v20140630
 * ==========================================================
 * Copyright hxw
 *
 * 大转盘抽奖js
 * ========================================================== */
// 调用方法:(转动的盘,几等奖,改奖品旋转角度,中奖之后执行的函数)
// rotateFunc(wheel,awards,angle,Fun)
// 如:rotateFunc($lotterywheel,3,90,function(){alertFun("获得三等奖")});

// (function(){
    var RotateTimeOut;//定时器
    var a = 0;//转的角度
    var c = 1;//旋转圈数
    //wheel:转动的区域(比如底盘), awards:奖项,angle:奖项对应的角度,text:提示文字
    var rotate = function(wheel,awards,angle,callback){
        if(navigator.userAgent.indexOf("MSIE 6.0") > 0 || navigator.userAgent.indexOf("MSIE 7.0")>0 || navigator.userAgent.indexOf("MSIE 8.0")>0){
            alert("请升级IE浏览器或使用其他浏览器参与抽奖")
        } else if(navigator.userAgent.indexOf("MSIE 9.0")>0){
            RotateTimeOut = setTimeout(function(){
                a += 1;
                if(a < angle){
                    wheel.css(‘-ms-transform‘,‘rotate(‘+ a +‘deg)‘);
                    rotate(wheel,awards,angle,callback);
                } else {
                    clearTimeout(RotateTimeOut);
                    callback();
                }
            },1);
        } else {
            // wheel.style.transform = ‘rotate(‘+ angle +‘deg)‘;
            // wheel.style.oTransform = ‘rotate(‘+ angle +‘deg)‘;
            // wheel[0].style.mozTransform = ‘rotate(‘+ angle +‘deg)‘;
            // wheel[0].style.webkitTransform = ‘rotate(‘+ angle +‘deg)‘;
            wheel.css(‘transform‘,‘rotate(‘+ angle +‘deg)‘);
            wheel.css(‘-webkit-transform‘,‘rotate(‘+ angle +‘deg)‘);
            wheel.css(‘-o-transform‘,‘rotate(‘+ angle +‘deg)‘);
            wheel.css(‘-moz-transform‘,‘rotate(‘+ angle +‘deg)‘);
            setTimeout(function(){callback()},2000);
        }
    };
    //参数(转动的盘,几等奖,改奖品旋转角度,中奖之后执行的函数)
    var rotateFunc = function(wheel,awards,angle,Fun){
        //2表示转2圈之后再到达获奖的位置
        var a = 2*360*c + angle;
        c++;
        rotate(wheel,awards,a,Fun);
    }
// })();

时间: 2024-10-12 16:40:19

大转盘抽奖的相关文章

纯CSS3大转盘抽奖(响应式、可配置)

源于前段时候微信小程序最初火爆公测时段,把以前用 Canvas 实现的大转盘抽奖移植成微信小程序,无奈当时小程序对 Canvas 支持不够完善,只好降低用 CSS3 实现.虽然比不上 Canvas 绘图的绚丽,但也总算完成了一个抽奖的 Demo,详见:https://github.com/givebest/wechat-turntalbe-canvas. 事后想起,CSS3 实现也并不是无有益处,比如简单.快捷.调试方便.渲染想来也是要比 Canvas 要高效的,更重要的一点是支持媒体查询,大转

jquery——九宫格大转盘抽奖

一.用到的图片 二.代码如下,重点是js部分 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>jQuery九宫格大转盘抽奖</title> <style> #lottery{width:570px;height:510p

原型导航应用于大转盘抽奖客户端显示页面实例

<html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <title>大转盘客户端</title> <meta name="keyw

大转盘抽奖css3+js(简单书写)

今天花了一段时间简单写了下抽奖大转盘,这里写的只是自己想到的简单的写了下(也希望收获其他想法),后续,再写的话会更新. 大体思路:页面加载完成后,通过监听开始按钮的点击事件.然后会根据产生的随机数,通过控制旋转针对象的transform属性,然后进行旋转,最后在结束后获取存储来数组中对应的抽奖内容最后弹出. 知识点:transform, translation,js数组,Math等等 先看下效果,没有素材,只是用css简单的布了下局.不要喷我比较简陋,嘿嘿. 接下来是基本代码结构: 1 <div

PHP新写的大转盘抽奖源码

中奖概率 抽奖大转盘演示:http://www.sucaihuo.com/php/3301.html function getRand($proArr, $proCount) { $result = ''; $proSum = 0; foreach ($proCount as $key => $val) { if ($val <= 0) { continue; } else { $proSum = $proSum + $proArr[$key]; } } foreach ($proArr as

利用jQueryRotate旋转插件开发大转盘抽奖

前言: 公司原来开发大转盘抽奖活动用的是flash 我发现swf文件竟然有6m大,吓尿了! 其实完全可以用js写的,但是自身前端功力有限,且时间紧迫,所以直接用旋转插件就好,兼容各方面都可以保证. 1.引用Jquery.js .jQueryRotate.2.2.js 插件 2.html代码: <div style="width: 480px;margin: 0 auto;height: 480px;background:url(http://weixin.maotui.cn/web/wec

原生js轮盘抽奖实例分析(幸运大转盘抽奖)

效果图: 所需图片素材: 这张图是pointer.png的位置的. turntable-bg.jpg这张是转盘背景图,在背景位置. 这张是turntable.png位置的. 需要这三张图片,如果要实现一下,直接另存这三图片引入进去即可.如果不会请修改成对应的图片名字,放到同一个文件下. 基本原理: 1,通过设置CSS样式的position属性,z-index属性等实现背景图,转盘图与指针图的层叠摆放: 2,通过设置元素style.transform = "rotate(0deg)"实现

九宫格大转盘抽奖

自己整理的希望能帮到一些人,我自己也是受益者,现在感觉好容易,只是逻辑有点小转看两遍也就会了,不比网站的强,而且不用花钱,还实用,自己延伸更易懂 html页面 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>抽奖</title> <link rel="stylesheet"

js幸运大转盘开发

最终效果实例下载:http://www.oschina.net/code/snippet_2352644_54997 一.大转盘准备工作 网上的一个抽奖大转盘实例http://www.jq22.com/yanshi2252 这就是我们要开发的效果,不过我们是让指针转,我们先分析这个效果: 结构有2部分,上面是指针背景图,下面是奖项图 点击指针元素开始抽奖,会转动一定圈数停下来 停下来的位置指针指使那个奖项,就会弹出获奖信息提示 这是参考效果,我们分析自己的大概实现: 同样上下2部分 点击指针转动