当前位置:首页 > 爱心点赞特效,飞心,类似淘宝的点赞效果代码

爱心点赞特效,飞心,类似淘宝的点赞效果代码

发布于 2019-01-31 阅读 438 次 CSS 移动端H5 CSS3 Canvas

效果预览

用到的小图片

源码

var paintZan = {
    init:function(){
        var self = this;
        self.img = new Image();
        self.img.src = 'http://image.w2le.com/9164ee3d6fb388ad01ffe99d55ca5f7c';
        self.img.onload = function(){
            self.createMap();
            rAF(self.paintHeart.bind(self));
        };
    },
    createMap:function(){
        this.canvas = document.getElementById('paint-zan');
        this.canvas.width=50;
        this.canvas.height=75;
        this.ctx = this.canvas.getContext('2d');
        this.heartsDatas = [];
        // this.heart();
    },
    heart:function(){
        var self = this,
            dir;
        if(self.heartsDatas.length%2==0){
            dir=-1;
        }else{
            dir=1;
        }
        self.heartsDatas.push({
            // img:zan,
            img:'https://yaoimage.lenovo.com.cn/static/prod/v2.1/images/zan.png',
            x:self.canvas.width/2-20/2,
            y:self.canvas.height-20,
            opacity:1,
            speed:0.5,
            dir:dir
        });
    },
    paintHeart:function(){
        var self = this;
        self.clearMap();
        for(var i=0;i<this.heartsDatas.length;i++){
            var ht = this.heartsDatas[i];
            if(ht.x >= 30){
                ht.dir=-1;
            }
            if(ht.x <= 0){
                ht.dir=1;
            }
            ht.x = ht.x+ht.dir*ht.speed;
            ht.y = ht.y - 1;
            self.ctx.save();
            self.ctx.translate(ht.x, ht.y);
            self.ctx.globalAlpha = (ht.y+window.bodyFontSize*0.24)/self.canvas.height;
            self.ctx.drawImage(self.img,0,0,27,24,0,0,20,18);
            self.ctx.fillStyle="#f60"
            // self.ctx.fillRect(0,0,20,18);
            self.ctx.restore();
        }
        rAF(self.paintHeart.bind(self));
    },
    clearMap:function(){
        this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
    },
    getRandom:function(min, max){
        return Math.floor(Math.random()*(max-min+1)+min);
    }
}

遇到的问题

在iphone上面drawImage 这个函数会有点问题,必须加载完图片绘制才有效果,但是我把onload写在save()之后发现出不来效果了,后来把图片加载放在最前面之后就没问题了。但是我想不明白为什么放在save之后不行,欢迎指导的大牛留言。

移动端的预览地址
用手机看效果好,pc暂时没做兼容