sprite.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. /**
  2. * 游戏基础的精灵类
  3. */
  4. function Sprite(imgSrc = '', x = 0, y = 0, width = 0, height = 0,iscircle=false) {
  5. this._width = width
  6. this._height = height
  7. this.x = x
  8. this.y = y
  9. this._name = ""
  10. this._fillStyle = "#ffffff"
  11. this._globalAlpha = 1;
  12. this.visible = true
  13. this.iscircle=iscircle
  14. this.src = imgSrc
  15. }
  16. Sprite.prototype = {
  17. set name(tex) {
  18. this._name = tex;
  19. },
  20. get name() {
  21. return this._name;
  22. },
  23. set width(tex) {
  24. this._width = tex;
  25. },
  26. get width() {
  27. return this._width;
  28. },
  29. set height(tex) {
  30. this._height = tex;
  31. },
  32. get height() {
  33. return this._height;
  34. },
  35. set fillStyle(tex) {
  36. this._fillStyle = tex;
  37. },
  38. set iscircle(iscircle) {
  39. this._iscircle = iscircle;
  40. },
  41. get globalAlpha() {
  42. return this._globalAlpha;
  43. },
  44. set globalAlpha(tex) {
  45. this._globalAlpha = tex;
  46. },
  47. get fillStyle() {
  48. return this._fillStyle;
  49. },
  50. set src(tex) {
  51. this._src = tex;
  52. if (tex != '' && tex != null) {
  53. this.img = wx.createImage();
  54. this.img.src = tex;
  55. this.img.onload = () => {
  56. if (this.ctx != null)
  57. if (this.parent) {
  58. this.parent.drawToCanvas(this.ctx);
  59. } else {
  60. this.drawToCanvas(this.ctx);
  61. }
  62. };
  63. }
  64. },
  65. get src() {
  66. return this._src;
  67. }
  68. }
  69. Sprite.prototype.position = function(x, y) {
  70. this.x = x;
  71. this.y = y;
  72. }
  73. /**
  74. * 将精灵图绘制在canvas上
  75. */
  76. Sprite.prototype.drawToCanvas = function(ctx) {
  77. if (!this.visible)
  78. return
  79. this.ctx = ctx;
  80. ctx.globalAlpha = this.globalAlpha;
  81. if (this.src != '' && this.src != null) {
  82. if (this._iscircle) {
  83. ctx.save();
  84. let r = Math.ceil(this.width * 0.5) ;
  85. ctx.arc(this.x + r, this.y + r, r, 0, Math.PI * 2);
  86. ctx.clip();
  87. ctx.drawImage(this.img, this.x, this.y, 2 * r, 2 * r);
  88. ctx.restore();
  89. } else {
  90. ctx.drawImage(this.img, this.x, this.y, this.width, this.height)
  91. }
  92. } else {
  93. ctx.fillStyle = this.fillStyle;
  94. ctx.fillRect(this.x, this.y, this.width, this.height);
  95. }
  96. }
  97. module.exports.Sprite = Sprite;