gblottery.js 12.2 KB
/**
 * Created by kkb on 15/8/31.
 */
;(function(){
    //定义画笔方法
    function ScratchCanvas(canvasid,option) {
        var $canvas = $('#'+canvasid),
            $canvas_container = $('.lottery-container'),
            context = $canvas[0].getContext('2d'),
            _canvasoffset = $canvas.offset(),
            _width = $canvas_container.width(),
            _height = $canvas_container.height(),
            _index = '',
            _option = {
                pensize: 20 ,//画笔直径,
                img: 'transparent'
            };
        _option = $.extend(_option,option);

        this.$canvas = $canvas;
        this.init = function(){
            var pattern = 'transparent',
                img = _option.img;
            _index = '';

            if(img){
                try{
                    pattern = context.createPattern(img,'no-repeat');
                }catch(e){
                    throw e;
                }
            }
            context.fillStyle = pattern;
            context.fillRect(0,0,_width,_height);
            context.globalCompositeOperation = 'destination-out';

        },
        this.setindex = function(index){
            _index = index;
        },
        this.getindex = function(){
          return _index;
        },
        this.setbackground = function(url){
            $canvas.css({
                'background-image':'url('+url+')',
                'background-repeat':'no-repeat'
            });
        },
        this.width = function(){
            return _width;
        },
        this.height = function(){
            return _height;
        },
        this.getarea = function(){
            var imgdata = context.getImageData(0,0,_width,_height).data,
                restarea = 0,
                i,
                len;
            for(i = 0 , len = imgdata.length ; i < len ; i += 4){
                if(imgdata[i] && imgdata[i+1] && imgdata[i+2] && imgdata[i+3]){
                    restarea ++;
                }
            }
            return restarea;
        },
        this.getpoint = function(pageX,pageY){
            return {
                x: pageX - _canvasoffset.left,
                y: pageY - _canvasoffset.top
            }
        },
        this.fillarc = function(point){
            var x = point.x,
                y = point.y,
                pensize = option.pensize;

            context.beginPath();
            context.moveTo(x,y)
            context.arc(x,y,pensize,0,2 * Math.PI,true);
            context.fill();
        },
        this.clear = function(){
            context.clearRect(0,0,_width,_height);
        };

    }
    //定义刮刮卡
    function ScratchCard(canvas,option){
        var _default = {
            rate: 0.8, //设置摸出80%触发事件
            fn: function(originalarr){ //默认随机算法
                    if(!originalarr || originalarr.length <= 0){
                        return;
                    }
                    var sumtotal = 0,
                        length = originalarr.length,
                        temparr = [],
                        temprate = 0,
                        i = 0,
                        nextindex;
                    for(; i < length ;i ++){
                        sumtotal += originalarr[i];
                    }

                    for(i = 0 ; i < length ; i ++){
                        temprate += originalarr[i];
                        temparr.push((temprate/sumtotal));
                    }

                    nextindex = Math.random();
                    temparr.push(nextindex);
                    temparr.sort();

                    return temparr.indexOf(nextindex);
                },
            gifts: []
            }; //默认参数
        this.mouse_down = false;
        this.canvas = canvas;
        this.option = $.extend(_default,option);
        this.startPoint = {};
    }
    //定义刮刮卡的事件
    ScratchCard.prototype = {
        constructor : ScratchCard,

        init: function(){
            var _this = this,
                _gifts = _this.option.gifts,
                _originalprobability = [],
                i,
                len,
                _index,
                _imgsrc = global_contextPath + '/',
                _img = new Image();
            if(_gifts.length > 0){
                for(i = 0 , len = _gifts.length ; i < len ; i ++){
                    _originalprobability.push(_gifts[i].probability);
                }
            }
            _index = _this.option.fn(_originalprobability);//随机抽奖
            _imgsrc += _gifts[_index].imgname;
            _img.src = _imgsrc; //浏览器去加载
            $(_img).on('load',function(){
                _this.canvas.setbackground(_imgsrc);
                _this.canvas.init();
                _this.canvas.setindex(_index);

                _this.canvas.$canvas.on('mousedown',function(event){
                    _this.mouseDown(event);
                });
                _this.canvas.$canvas.on('touchstart',function(event){
                    _this.mouseDown(event);
                });
                _this.canvas.$canvas.on('mouseup',function(event){
                    _this.mouseUp(event);
                });
                _this.canvas.$canvas.on('mouseout',function(event){
                    _this.mouseUp(event);
                });
                _this.canvas.$canvas.on('touchend',function(event){
                    _this.mouseUp(event);
                });
                _this.canvas.$canvas.on('mousemove',function(event){
                    _this.mouseMove(event);
                });
                _this.canvas.$canvas.on('touchmove',function(event){
                    _this.mouseMove(event);
                });
            });
        },
        pageOffset: function(event){
            return{
                pageX: event.pageX? event.pageX : event.changedTouches[0].pageX,
                pageY: event.pageY? event.pageY : event.changedTouches[0].pageY
            }
        },
        mouseDown: function(event){
            event.preventDefault();
            var pageoffset = this.pageOffset(event);
            this.mouse_down = true;
            this.startPoint = this.canvas.getpoint(pageoffset.pageX,pageoffset.pageY);
        },
        mouseUp: function(event){
            event.preventDefault();
            this.mouse_down = false;
            var restarea = this.canvas.getarea();
            if(restarea < this.canvas.width() * this.canvas.height() * (1-this.option.rate) && $.isFunction(this.option.callback)){
                var award = this.option.gifts[this.canvas.getindex()];
                if(award){
                    this.option.callback(award);
                }
                this.canvas.setindex('');
            }
        },
        mouseMove: function(event){
            if(!this.mouse_down){
                return;
            }
            //解决快速滑动的断点问题
            var p = this.canvas.getpoint(this.pageOffset(event).pageX,this.pageOffset(event).pageY),
                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.canvas.fillarc({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.canvas.fillarc({x: i, y: (this.startPoint.y + ( i - this.startPoint.x  ) * k)});
                }
            }
            this.startPoint = p;
        }
    };
    (function(){
        var uid = global_onlineuser.uid,
            isCheckedIn = false,
            $lottery_container = $('.lottery-container');
        if(uid > 0 && $lottery_container.length > 0){
            identityService.findUserLotteryByUid({
                callback: function(gbdata){
                    //页面初始化
                    $('.lottery-container').show();
                    var scratch_canvas = new ScratchCanvas('lottery-canvas',{
                            pensize: 68,
                            img: $('.lottery-container img')[0]
                        }),
                        scratch_card = new ScratchCard(scratch_canvas,{
                            gifts:[{
                                name: 'coin',
                                probability: 0.20,
                                imgname: 'networks/themes/img/money.png'
                            },{
                                name: '',
                                probability: 0.80,
                                imgname: 'networks/themes/img/nothing.png'
                            }],
                            rate: 0.23,
                            callback: function(award){
                                //console.log('获得奖品'+award.name);
                                var uid,
                                    coin = 0,
                                    range = ['1','5'];
                                if(award.name == 'coin'){
                                    coin = Math.floor(Math.random()*(parseInt(range[1])-parseInt(range[0]) + 1) + parseInt(range[0]));
                                    $.msg({
                                        buttons:[
                                            {
                                                '知道了': $.noop
                                            }
                                        ],
                                        msg:'运气不错,获得'+coin+'个金币'
                                    });
                                }else{
                                    coin = 0;
                                    $.msg({
                                        buttons:[
                                            {
                                                '好的': $.noop
                                            }
                                        ],
                                        msg:'运气不佳,明日再来'
                                    });
                                }
                                identityService.saveLastLotteryDateByUid(coin,{
                                    callback: function(gbdata){}
                                });
                            }
                        });
                    if(gbdata){
                        scratch_card.init();
                    }else{
                        isCheckedIn = true;
                    }
                    $('.lottery-container').hide();
                    !isCheckedIn?
                    	$('.lottery-container').show().addClass('show-canvas swing3d'):
                    	'';
                }
            });
        }
		
        //点击签到
        $('.check-in-btn').click(function(){
            if(uid > 0){
                if(!isCheckedIn){
                    if($('.lottery-container').is(':visible')){
                        return;
                    }
                    $('.lottery-container').show().addClass('show-canvas swing3d');
                }else{
                    $.msg({
                        buttons:[{
                            '好的': $.noop
                        }],
                        msg: '今天已经签过了,明天继续'
                    });
                }
            }else{
                $.msg({
                    buttons:[
                        {
                            '登录':function(){
                                window.location.href = 'http://www.gbtags.com/gb/syslogin.htm';
                            }
                        }
                    ],
                    msg: '登录后才能签到'
                });
            }
        });
    })();
	
})();



//最近一周的中奖用户~~
$(document).ready(function() {
	
	var thistemplate = $("#gb-getlotteryusers-tmpl");
	
	if(thistemplate.length){
		identityService.findLatestGetLotteryUser({
			callback:function(gbdata){	
				var template = Handlebars.compile(thistemplate.html()), 
							        	userlist = template(gbdata);
	
				$('#lotterywithinweekusers').append(userlist);
			}	
		});
	}

});