Toast.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. //一个简单的tost组件,用法:
  2. // let Toast = reqire('Toast.js')
  3. // Toast(text,{gravity,duration,bg_color})
  4. //text:要显示的字符串
  5. //gravity(可选):位置,String类型,可选值('CENTER','TOP','BOTTOM'),默认为'CENTER'
  6. //duration(可选):时间,Number类型,单位为秒,默认1s
  7. //bg_color(可选):颜色,cc.color类型,默认cc.color(102, 102, 102, 200)
  8. function Toast(
  9. text = "",
  10. {
  11. gravity = "CENTER",
  12. duration = 1,
  13. bg_color = cc.color(102, 102, 102, 200)
  14. } = {}
  15. ) {
  16. // canvas
  17. let canvas = cc.director.getScene().getComponentInChildren(cc.Canvas);
  18. let width = canvas.node.width;
  19. let height = canvas.node.height;
  20. let bgNode = new cc.Node();
  21. // Lable文本格式设置
  22. let textNode = new cc.Node();
  23. let textLabel = textNode.addComponent(cc.Label);
  24. textLabel.horizontalAlign = cc.Label.HorizontalAlign.CENTER;
  25. textLabel.verticalAlign = cc.Label.VerticalAlign.CENTER;
  26. textLabel.fontSize = 30;
  27. textLabel.string = text;
  28. // 当文本宽度过长时,设置为自动换行格式
  29. if (text.length * textLabel.fontSize > (width * 3) / 5) {
  30. textNode.width = (width * 3) / 5;
  31. textLabel.overflow = cc.Label.Overflow.RESIZE_HEIGHT;
  32. } else {
  33. textNode.width = text.length * textLabel.fontSize;
  34. }
  35. let lineCount =
  36. ~~((text.length * textLabel.fontSize) / ((width * 3) / 5)) + 1;
  37. textNode.height = textLabel.fontSize * lineCount;
  38. // 背景设置
  39. let ctx = bgNode.addComponent(cc.Graphics);
  40. ctx.arc(
  41. -textNode.width / 2,
  42. 0,
  43. textNode.height / 2 + 20,
  44. 0.5 * Math.PI,
  45. 1.5 * Math.PI,
  46. true
  47. );
  48. ctx.lineTo(textNode.width / 2, -(textNode.height / 2 + 20));
  49. ctx.arc(
  50. textNode.width / 2,
  51. 0,
  52. textNode.height / 2 + 20,
  53. 1.5 * Math.PI,
  54. 0.5 * Math.PI,
  55. true
  56. );
  57. ctx.lineTo(-textNode.width / 2, textNode.height / 2 + 20);
  58. ctx.fillColor = bg_color;
  59. ctx.fill();
  60. bgNode.addChild(textNode);
  61. // gravity 设置Toast显示的位置
  62. if (gravity === "CENTER") {
  63. bgNode.y = 0;
  64. bgNode.x = 0;
  65. } else if (gravity === "TOP") {
  66. bgNode.y = bgNode.y + (height / 5) * 2;
  67. } else if (gravity === "BOTTOM") {
  68. bgNode.y = bgNode.y - (height / 5) * 2;
  69. }
  70. canvas.node.addChild(bgNode);
  71. let finished = cc.callFunc(function() {
  72. bgNode.destroy();
  73. });
  74. let action = cc.sequence(
  75. cc.moveBy(duration, cc.v2(0, 0)),
  76. cc.fadeOut(0.3),
  77. finished
  78. );
  79. bgNode.runAction(action);
  80. }
  81. module.exports = Toast;