so://phie

outline

A web-based drawing app
git clone git://soophie.de/outline

blob: 4f7c02b0bc1e1698151a889288b319569ebc7db9 (2488 bytes)[doc][blame][raw]

1import { COLORS } from '../constant.js';

2

3let active;

4let point_list = [];

5

6let canvas;

7let overlay;

8let memory;

9

10function init() {

11 canvas = document.querySelector('#canvas');

12 overlay = document.querySelector('#overlay');

13 memory = document.createElement('canvas');

14 fit(canvas);

15 fit(overlay);

16 fit(memory);

17 window.addEventListener('resize', function(event) {

18 resize(canvas);

19 resize(overlay);

20 resize(memory);

21 });

22}

23

24function fit(canvas) {

25 canvas.width = window.innerWidth;

26 canvas.height = window.innerHeight;

27}

28

29function get(canvas) {

30 return canvas.getContext('2d');

31}

32

33function get_canvas() {

34 return canvas;

35}

36

37function resize(canvas) {

38 let g = get(canvas);

39 let image_data = g.getImageData(0, 0, canvas.width, canvas.height);

40 fit(canvas);

41 g.putImageData(image_data, 0, 0);

42}

43

44function clear() {

45 get(canvas).clearRect(0, 0, canvas.width, canvas.height);

46 get(memory).clearRect(0, 0, memory.width, memory.height);

47}

48

49function on_press(event) {

50 active = true;

51 point_list.push({

52 x: event.layerX,

53 y: event.layerY

54 });

55}

56

57function on_move(event, state) {

58 if(active) {

59 get(canvas).clearRect(0, 0, canvas.width, canvas.height);

60 get(canvas).drawImage(memory, 0, 0);

61 point_list.push({

62 x: event.layerX,

63 y: event.layerY

64 });

65 draw_curve(state);

66 }

67}

68

69function on_release(event) {

70 if(active) {

71 if(event.type === 'pointerup') {

72 active = false;

73 }

74 get(memory).clearRect(0, 0, memory.width, memory.height);

75 get(memory).drawImage(canvas, 0, 0);

76 point_list = [];

77 }

78}

79

80function draw_curve(state) {

81 let g = get(canvas);

82 g.lineJoin = 'round';

83 g.lineCap = 'round';

84 g.lineWidth = 2 * state.radius;

85 g.strokeStyle = COLORS[state.color] + 'BB';

86 if(point_list.length < 3) {

87 return;

88 }

89 if(point_list.length < 3) {

90 g.beginPath();

91 g.arc(point_list[0].x + 0.5, point_list[0].y + 0.5, g.lineWidth / 2, 0, Math.PI * 2, !0);

92 g.closePath();

93 g.fill();

94 return;

95 }

96 g.beginPath();

97 g.moveTo(point_list[0].x + 0.5, point_list[0].y + 0.5);

98 let i;

99 for(i = 1; i < point_list.length - 2; i++) {

100 let dx = (point_list[i].x + point_list[i + 1].x);

101 let dy = (point_list[i].y + point_list[i + 1].y);

102 g.quadraticCurveTo(point_list[i].x + 0.5, point_list[i].y + 0.5, (dx / 2) + 0.5, (dy / 2) + 0.5);

103 }

104 g.quadraticCurveTo(point_list[i].x + 0.5, point_list[i].y + 0.5, point_list[i + 1].x + 0.5, point_list[i + 1].y + 0.5);

105 g.stroke();

106}

107

108export default {

109 init,

110 fit,

111 get,

112 get_canvas,

113 resize,

114 clear,

115 on_press,

116 on_move,

117 on_release,

118 draw_curve

119};