DrawHelper.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. export default class DrawHelper {
  2. fontBySize(size) {
  3. return `${size}px ${this.fontName}`;
  4. }
  5. drawPercentBar(context, x, y, w, h, bookPos, textLength) {
  6. const pad = 3;
  7. const fh = h - 2*pad;
  8. const fh2 = fh/2;
  9. const t1 = `${Math.floor((bookPos + 1)/1000)}k/${Math.floor(textLength/1000)}k`;
  10. const w1 = context.measureText(t1).width + fh2;
  11. const read = (bookPos + 1)/textLength;
  12. const t2 = `${(read*100).toFixed(2)}%`;
  13. const w2 = context.measureText(t2).width;
  14. let w3 = w - w1 - w2;
  15. if (w1 + w2 <= w)
  16. context.fillText(t1, x, y + h - 2);
  17. if (w1 + w2 + w3 <= w && w3 > (10 + fh2)) {
  18. const barWidth = w - w1 - w2 - fh2;
  19. context.strokeRect(x + w1, y + pad + 1, barWidth, fh - 2);
  20. context.fillRect(x + w1 + 2, y + pad + 3, (barWidth - 4)*read, fh - 6);
  21. }
  22. if (w1 <= w)
  23. context.fillText(t2, x + w1 + w3, y + h - 2);
  24. }
  25. async drawStatusBar(context, statusBarTop, statusBarHeight, statusBarColor, bookPos, textLength, title) {
  26. const y = (statusBarTop ? 1 : this.realHeight - statusBarHeight);
  27. context.fillStyle = this.backgroundColor;
  28. context.fillRect(0, y, this.realWidth, statusBarHeight);
  29. context.font = 'bold ' + this.fontBySize(statusBarHeight - 6);
  30. context.fillStyle = statusBarColor;
  31. context.strokeStyle = statusBarColor;
  32. context.fillRect(0, (statusBarTop ? statusBarHeight : y), this.realWidth, 1);
  33. const date = new Date();
  34. const time = ` ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')} `;
  35. const timeW = context.measureText(time).width;
  36. context.fillText(time, this.realWidth - timeW, y + statusBarHeight - 2);
  37. title = ' ' + title;
  38. context.fillText(this.fittingString(context, title, this.realWidth/2 - 3), 0, y + statusBarHeight - 2);
  39. this.drawPercentBar(context, this.realWidth/2, y, this.realWidth/2 - timeW, statusBarHeight, bookPos, textLength);
  40. }
  41. fittingString(context, str, maxWidth) {
  42. let w = context.measureText(str).width;
  43. const ellipsis = '…';
  44. const ellipsisWidth = context.measureText(ellipsis).width;
  45. if (w <= maxWidth || w <= ellipsisWidth) {
  46. return str;
  47. } else {
  48. let len = str.length;
  49. while (w >= maxWidth - ellipsisWidth && len-- > 0) {
  50. str = str.substring(0, len);
  51. w = context.measureText(str).width;
  52. }
  53. return str + ellipsis;
  54. }
  55. }
  56. }