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

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

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

效果预览

用到的小图片

源码

  1. var paintZan = {
  2. init:function(){
  3. var self = this;
  4. self.img = new Image();
  5. self.img.src = 'http://image.w2le.com/9164ee3d6fb388ad01ffe99d55ca5f7c';
  6. self.img.onload = function(){
  7. self.createMap();
  8. rAF(self.paintHeart.bind(self));
  9. };
  10. },
  11. createMap:function(){
  12. this.canvas = document.getElementById('paint-zan');
  13. this.canvas.width=50;
  14. this.canvas.height=75;
  15. this.ctx = this.canvas.getContext('2d');
  16. this.heartsDatas = [];
  17. // this.heart();
  18. },
  19. heart:function(){
  20. var self = this,
  21. dir;
  22. if(self.heartsDatas.length%2==0){
  23. dir=-1;
  24. }else{
  25. dir=1;
  26. }
  27. self.heartsDatas.push({
  28. // img:zan,
  29. img:'https://yaoimage.lenovo.com.cn/static/prod/v2.1/images/zan.png',
  30. x:self.canvas.width/2-20/2,
  31. y:self.canvas.height-20,
  32. opacity:1,
  33. speed:0.5,
  34. dir:dir
  35. });
  36. },
  37. paintHeart:function(){
  38. var self = this;
  39. self.clearMap();
  40. for(var i=0;i<this.heartsDatas.length;i++){
  41. var ht = this.heartsDatas[i];
  42. if(ht.x >= 30){
  43. ht.dir=-1;
  44. }
  45. if(ht.x <= 0){
  46. ht.dir=1;
  47. }
  48. ht.x = ht.x+ht.dir*ht.speed;
  49. ht.y = ht.y - 1;
  50. self.ctx.save();
  51. self.ctx.translate(ht.x, ht.y);
  52. self.ctx.globalAlpha = (ht.y+window.bodyFontSize*0.24)/self.canvas.height;
  53. self.ctx.drawImage(self.img,0,0,27,24,0,0,20,18);
  54. self.ctx.fillStyle="#f60"
  55. // self.ctx.fillRect(0,0,20,18);
  56. self.ctx.restore();
  57. }
  58. rAF(self.paintHeart.bind(self));
  59. },
  60. clearMap:function(){
  61. this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
  62. },
  63. getRandom:function(min, max){
  64. return Math.floor(Math.random()*(max-min+1)+min);
  65. }
  66. }

遇到的问题

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

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