line.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.createLinePattern = exports.drawLine = exports.defaultLinePatternCfg = void 0;
  4. var utils_1 = require("../../utils");
  5. var util_1 = require("./util");
  6. /**
  7. * linePattern 的 默认配置
  8. */
  9. exports.defaultLinePatternCfg = {
  10. rotation: 45,
  11. spacing: 5,
  12. opacity: 1,
  13. backgroundColor: 'transparent',
  14. strokeOpacity: 0.5,
  15. stroke: '#fff',
  16. lineWidth: 2,
  17. };
  18. /**
  19. * 绘制line
  20. *
  21. * @param context canvasContext
  22. * @param cfg linePattern 的配置
  23. * @param d 绘制 path 所需的 d
  24. */
  25. function drawLine(context, cfg, d) {
  26. var stroke = cfg.stroke, lineWidth = cfg.lineWidth, strokeOpacity = cfg.strokeOpacity;
  27. var path = new Path2D(d);
  28. context.globalAlpha = strokeOpacity;
  29. context.lineCap = 'square';
  30. context.strokeStyle = lineWidth ? stroke : 'transparent';
  31. context.lineWidth = lineWidth;
  32. context.stroke(path);
  33. }
  34. exports.drawLine = drawLine;
  35. /**
  36. * 创建 linePattern
  37. */
  38. function createLinePattern(cfg) {
  39. var lineCfg = (0, utils_1.deepAssign)({}, exports.defaultLinePatternCfg, cfg);
  40. var spacing = lineCfg.spacing, rotation = lineCfg.rotation, lineWidth = lineCfg.lineWidth;
  41. // 计算 pattern 画布的大小, path 所需的 d
  42. var width = spacing + lineWidth || 1;
  43. var height = spacing + lineWidth || 1;
  44. var d = "\n M 0 0 L ".concat(width, " 0\n M 0 ").concat(height, " L ").concat(width, " ").concat(height, "\n ");
  45. // 初始化 patternCanvas
  46. var canvas = (0, util_1.initCanvas)(width, height);
  47. var ctx = canvas.getContext('2d');
  48. // 绘制 background,line
  49. (0, util_1.drawBackground)(ctx, lineCfg, width, height);
  50. drawLine(ctx, lineCfg, d);
  51. var pattern = ctx.createPattern(canvas, 'repeat');
  52. if (pattern) {
  53. var dpr = (0, util_1.getPixelRatio)();
  54. var matrix = (0, util_1.transformMatrix)(dpr, rotation);
  55. pattern.setTransform(matrix);
  56. }
  57. // 返回 Pattern 对象
  58. return pattern;
  59. }
  60. exports.createLinePattern = createLinePattern;
  61. //# sourceMappingURL=line.js.map