canvas.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. setFont({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. // fs = toPx(fs)
  19. ctx.font = `${ts} ${fw} ${fs}px ${ff}`;
  20. },
  21. // #ifndef APP-PLUS
  22. measureText(text, fontSize) {
  23. // app measureText为0需要累加计算0
  24. return {
  25. width: text.split("").reduce((widthScaleSum, char) => {
  26. let code = char.charCodeAt(0);
  27. let widthScale = CHAR_WIDTH_SCALE_MAP[code - 0x20] || 1;
  28. return widthScaleSum + widthScale;
  29. }, 0) * fontSize
  30. };
  31. }
  32. // #endif
  33. }
  34. }
  35. export function expand(ctx) {
  36. return Object.assign(ctx, _expand(ctx))
  37. }
  38. export function adaptor(ctx) {
  39. return Object.assign(ctx, _expand(ctx), {
  40. setStrokeStyle(val) {
  41. ctx.strokeStyle = val;
  42. },
  43. setLineWidth(val) {
  44. ctx.lineWidth = val;
  45. },
  46. setLineCap(val) {
  47. ctx.lineCap = val;
  48. },
  49. setFillStyle(val) {
  50. ctx.fillStyle = val;
  51. },
  52. setFontSize(val) {
  53. ctx.font = String(val);
  54. },
  55. setGlobalAlpha(val) {
  56. ctx.globalAlpha = val;
  57. },
  58. setLineJoin(val) {
  59. ctx.lineJoin = val;
  60. },
  61. setTextAlign(val) {
  62. ctx.textAlign = val;
  63. },
  64. setMiterLimit(val) {
  65. ctx.miterLimit = val;
  66. },
  67. setShadow(offsetX, offsetY, blur, color) {
  68. ctx.shadowOffsetX = offsetX;
  69. ctx.shadowOffsetY = offsetY;
  70. ctx.shadowBlur = blur;
  71. ctx.shadowColor = color;
  72. },
  73. setTextBaseline(val) {
  74. ctx.textBaseline = val;
  75. },
  76. createCircularGradient() {},
  77. draw() {},
  78. });
  79. }