line.js 1.8 KB

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