canvas.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { CHAR_WIDTH_SCALE_MAP } from './utils'
  2. const _expand = ctx => {
  3. // #ifndef APP-PLUS
  4. ctx._measureText = ctx.measureText
  5. // #endif
  6. return {
  7. setFonts({fontFamily: ff = 'sans-serif', fontSize: fs = 14, fontWeight: fw = 'normal' , textStyle: ts = 'normal'}) {
  8. // let ctx = this.ctx
  9. // 设置属性
  10. // #ifndef MP-TOUTIAO
  11. // fw = fw == 'bold' ? 'bold' : 'normal'
  12. // ts = ts == 'italic' ? 'italic' : 'normal'
  13. // #endif
  14. // #ifdef MP-TOUTIAO
  15. fw = fw == 'bold' ? 'bold' : ''
  16. ts = ts == 'italic' ? 'italic' : ''
  17. // #endif
  18. ctx.font = `${ts} ${fw} ${fs}px ${ff}`;
  19. },
  20. // #ifndef APP-PLUS
  21. measureText(text, fontSize) {
  22. // app measureText为0需要累加计算0
  23. return {
  24. width: text.split("").reduce((widthScaleSum, char) => {
  25. let code = char.charCodeAt(0);
  26. let widthScale = CHAR_WIDTH_SCALE_MAP[code - 0x20] || 1;
  27. return widthScaleSum + widthScale;
  28. }, 0) * fontSize
  29. };
  30. },
  31. // #endif
  32. }
  33. };
  34. export function expand(ctx) {
  35. return Object.assign(ctx, _expand(ctx))
  36. }
  37. export function adaptor(ctx) {
  38. return Object.assign(ctx, _expand(ctx), {
  39. setStrokeStyle(val) {
  40. ctx.strokeStyle = val;
  41. },
  42. setLineWidth(val) {
  43. ctx.lineWidth = val;
  44. },
  45. setLineCap(val) {
  46. ctx.lineCap = val;
  47. },
  48. setFillStyle(val) {
  49. ctx.fillStyle = val;
  50. },
  51. setFontSize(val) {
  52. ctx.font = String(val);
  53. },
  54. setGlobalAlpha(val) {
  55. ctx.globalAlpha = val;
  56. },
  57. setLineJoin(val) {
  58. ctx.lineJoin = val;
  59. },
  60. setTextAlign(val) {
  61. ctx.textAlign = val;
  62. },
  63. setMiterLimit(val) {
  64. ctx.miterLimit = val;
  65. },
  66. setShadow(offsetX, offsetY, blur, color) {
  67. ctx.shadowOffsetX = offsetX;
  68. ctx.shadowOffsetY = offsetY;
  69. ctx.shadowBlur = blur;
  70. ctx.shadowColor = color;
  71. },
  72. setTextBaseline(val) {
  73. ctx.textBaseline = val;
  74. },
  75. createCircularGradient() {},
  76. draw() {},
  77. });
  78. }