Message.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var Message = function(msg) {
  2. var message = this;
  3. this.age = 1;
  4. this.maxAge = 300;
  5. this.message = msg;
  6. this.update = function() {
  7. this.age++;
  8. }
  9. this.draw = function(context,x,y,i) {
  10. var fontsize = 8;
  11. context.font = fontsize + "px 'proxima-nova-1','proxima-nova-2', arial, sans-serif";
  12. context.textBaseline = 'hanging';
  13. var paddingH = 3;
  14. var paddingW = 6;
  15. var messageBox = {
  16. width: context.measureText(message.message).width + paddingW * 2,
  17. height: fontsize + paddingH * 2,
  18. x: x,
  19. y: (y - i * (fontsize + paddingH * 2 +1))-20
  20. }
  21. var fadeDuration = 20;
  22. var opacity = (message.maxAge - message.age) / fadeDuration;
  23. opacity = opacity < 1 ? opacity : 1;
  24. context.fillStyle = 'rgba(255,255,255,'+opacity/20+')';
  25. drawRoundedRectangle(context, messageBox.x, messageBox.y, messageBox.width, messageBox.height, 10);
  26. context.fillStyle = 'rgba(255,255,255,'+opacity+')';
  27. context.fillText(message.message, messageBox.x + paddingW, messageBox.y + paddingH, 100);
  28. }
  29. var drawRoundedRectangle = function(ctx,x,y,w,h,r) {
  30. var r = r / 2;
  31. ctx.beginPath();
  32. ctx.moveTo(x, y+r);
  33. ctx.lineTo(x, y+h-r);
  34. ctx.quadraticCurveTo(x, y+h, x+r, y+h);
  35. ctx.lineTo(x+w-r, y+h);
  36. ctx.quadraticCurveTo(x+w, y+h, x+w, y+h-r);
  37. ctx.lineTo(x+w, y+r);
  38. ctx.quadraticCurveTo(x+w, y, x+w-r, y);
  39. ctx.lineTo(x+r, y);
  40. ctx.quadraticCurveTo(x, y, x, y+r);
  41. ctx.closePath();
  42. ctx.fill();
  43. }
  44. }