sketch.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /*
  2. ArozOS Office - drawing canvas (common/sketch.js)
  3. =================================================
  4. The Draw tab of Docs and Slides: a freehand drawing pad in a dialog
  5. (pens, highlighters, an eraser, undo), inserted into the document as a
  6. picture - a transparent PNG cropped to what was drawn, rendered at twice
  7. the size it is shown so it stays crisp when printed. A picture is what
  8. every format the suite writes can hold, which is why the strokes are not
  9. kept as vectors.
  10. OfficeSketch.open({
  11. title: "Drawing",
  12. pen: "pen-red", // a PENS id to start with (optional)
  13. aspect: 9 / 16, // canvas height / width (optional)
  14. onInsert: function (blob, w, h) { ... } // PNG, its size in CSS px
  15. });
  16. OfficeSketch.PENS // the presets the ribbon shows
  17. OfficeSketch.penIcon(pen) // an SVG of that pen, for a button
  18. */
  19. var OfficeSketch = (function () {
  20. "use strict";
  21. var PENS = [
  22. { id: "pen-black", kind: "pen", color: "#202124", width: 3, label: "Pen" },
  23. { id: "pen-red", kind: "pen", color: "#d0342c", width: 3, label: "Red pen" },
  24. { id: "pen-blue", kind: "pen", color: "#1a73e8", width: 3, label: "Blue pen" },
  25. { id: "pen-green", kind: "pen", color: "#188038", width: 3, label: "Green pen" },
  26. { id: "marker-yellow", kind: "marker", color: "#ffd400", width: 16, label: "Highlighter" },
  27. { id: "marker-green", kind: "marker", color: "#5ce07a", width: 16, label: "Green highlighter" }
  28. ];
  29. var WIDTHS = [1, 2, 3, 5, 8, 12, 16, 24];
  30. var MARKER_ALPHA = 0.45;
  31. function esc(t) { return OfficeApp.escapeHtml(t); }
  32. function penById(id) {
  33. for (var i = 0; i < PENS.length; i++) if (PENS[i].id === id) return PENS[i];
  34. return PENS[0];
  35. }
  36. function penIcon(p) {
  37. if (p.kind === "marker") {
  38. return '<svg class="of-ic" viewBox="0 0 24 24" aria-hidden="true">' +
  39. '<path d="M15 3l6 6-8.5 8.5-6-6z"/><path d="M6.5 11.5 4 18l2 2 6.5-2.5"/>' +
  40. '<path d="M3 21.5h9" stroke="' + p.color + '" stroke-width="3" opacity=".8"/></svg>';
  41. }
  42. return '<svg class="of-ic" viewBox="0 0 24 24" aria-hidden="true">' +
  43. '<path d="M4 20l1.4-5.2L16 4.2l3.8 3.8L9.2 18.6z"/><path d="M13.5 6.7l3.8 3.8"/>' +
  44. '<path d="M4 20l1.4-5.2 3.8 3.8z" fill="' + p.color + '" stroke="' + p.color + '"/></svg>';
  45. }
  46. /* ---------- drawing ---------- */
  47. function drawStroke(ctx, s) {
  48. var p = s.pts;
  49. if (!p.length) return;
  50. ctx.save();
  51. ctx.globalAlpha = s.kind === "marker" ? MARKER_ALPHA : 1;
  52. ctx.strokeStyle = s.color;
  53. ctx.fillStyle = s.color;
  54. ctx.lineWidth = s.width;
  55. ctx.lineCap = s.kind === "marker" ? "square" : "round";
  56. ctx.lineJoin = "round";
  57. if (p.length === 1) {
  58. ctx.beginPath();
  59. ctx.arc(p[0][0], p[0][1], s.width / 2, 0, Math.PI * 2);
  60. ctx.fill();
  61. ctx.restore();
  62. return;
  63. }
  64. // a quadratic through the midpoints: smooth, and it still passes
  65. // close to every sample
  66. ctx.beginPath();
  67. ctx.moveTo(p[0][0], p[0][1]);
  68. for (var i = 1; i < p.length - 1; i++) {
  69. var mx = (p[i][0] + p[i + 1][0]) / 2, my = (p[i][1] + p[i + 1][1]) / 2;
  70. ctx.quadraticCurveTo(p[i][0], p[i][1], mx, my);
  71. }
  72. var last = p[p.length - 1];
  73. ctx.lineTo(last[0], last[1]);
  74. ctx.stroke();
  75. ctx.restore();
  76. }
  77. function bounds(strokes) {
  78. var b = null;
  79. strokes.forEach(function (s) {
  80. var r = s.width / 2 + 2;
  81. s.pts.forEach(function (q) {
  82. if (!b) b = { x1: q[0] - r, y1: q[1] - r, x2: q[0] + r, y2: q[1] + r };
  83. b.x1 = Math.min(b.x1, q[0] - r);
  84. b.y1 = Math.min(b.y1, q[1] - r);
  85. b.x2 = Math.max(b.x2, q[0] + r);
  86. b.y2 = Math.max(b.y2, q[1] + r);
  87. });
  88. });
  89. return b;
  90. }
  91. function hits(s, x, y, r) {
  92. var lim = r + s.width / 2;
  93. for (var i = 0; i < s.pts.length; i++) {
  94. var dx = s.pts[i][0] - x, dy = s.pts[i][1] - y;
  95. if (dx * dx + dy * dy <= lim * lim) return true;
  96. if (i > 0) {
  97. // the segment between two samples, for fast strokes
  98. var ax = s.pts[i - 1][0], ay = s.pts[i - 1][1];
  99. var bx = s.pts[i][0], by = s.pts[i][1];
  100. var vx = bx - ax, vy = by - ay;
  101. var len = vx * vx + vy * vy;
  102. if (len > 0) {
  103. var t = Math.max(0, Math.min(1, ((x - ax) * vx + (y - ay) * vy) / len));
  104. var px = ax + t * vx - x, py = ay + t * vy - y;
  105. if (px * px + py * py <= lim * lim) return true;
  106. }
  107. }
  108. }
  109. return false;
  110. }
  111. /* ---------- the dialog ---------- */
  112. function open(o) {
  113. o = o || {};
  114. var start = penById(o.pen);
  115. var tool = { kind: start.kind, color: start.color, width: start.width, eraser: false };
  116. var penId = start.id; // the preset in hand, "" for a custom colour
  117. var strokes = [];
  118. var history = [[]], hpos = 0;
  119. var cur = null;
  120. var vw = Math.min(800, Math.max(260, window.innerWidth * 0.94 - 40));
  121. var cw = Math.round(vw);
  122. var ch = Math.round(Math.min(window.innerHeight * 0.6, cw * (o.aspect || 0.56)));
  123. var dpr = Math.max(1, Math.min(3, window.devicePixelRatio || 1));
  124. var $b = $('<div class="of-sketch"></div>');
  125. var $bar = $('<div class="of-sketch-bar"></div>');
  126. var $pens = $('<div class="of-sketch-pens"></div>');
  127. PENS.forEach(function (p) {
  128. var $p = $('<button type="button" class="of-tbtn of-sketch-pen"></button>')
  129. .attr("title", p.label).attr("data-pen", p.id).html(penIcon(p));
  130. $p.on("click", function () {
  131. tool = { kind: p.kind, color: p.color, width: p.width, eraser: false };
  132. $color.val(p.color).trigger("of-cp-refresh");
  133. $width.val(String(p.width));
  134. penId = p.id;
  135. syncBar();
  136. });
  137. $pens.append($p);
  138. });
  139. var $eraser = $('<button type="button" class="of-tbtn" title="Eraser - removes whole strokes"><i class="eraser icon"></i></button>');
  140. $eraser.on("click", function () { tool.eraser = !tool.eraser; syncBar(); });
  141. var $color = OfficeColorPicker.swatchInput({ title: "Ink colour", value: start.color });
  142. $color.on("change", function () {
  143. tool.color = $color.val() || tool.color;
  144. tool.eraser = false;
  145. penId = "";
  146. syncBar();
  147. });
  148. var $width = $('<select class="of-tselect" title="Thickness"></select>');
  149. WIDTHS.forEach(function (w) { $width.append($("<option></option>").attr("value", w).text(w + " px")); });
  150. if (WIDTHS.indexOf(start.width) < 0) $width.append($("<option></option>").attr("value", start.width).text(start.width + " px"));
  151. $width.val(String(start.width));
  152. $width.on("change", function () { tool.width = parseInt($width.val(), 10) || 3; });
  153. var $undo = $('<button type="button" class="of-tbtn" title="Undo"><i class="undo icon"></i></button>');
  154. var $redo = $('<button type="button" class="of-tbtn" title="Redo"><i class="redo icon"></i></button>');
  155. var $clear = $('<button type="button" class="of-tbtn" title="Clear"><i class="trash alternate outline icon"></i></button>');
  156. $bar.append($pens).append('<span class="of-tsep"></span>').append($eraser)
  157. .append('<span class="of-tsep"></span>').append($color).append($width)
  158. .append('<span class="of-tsep"></span>').append($undo).append($redo).append($clear);
  159. $b.append($bar);
  160. var $wrap = $('<div class="of-sketch-paper"></div>').css({ width: cw + "px", height: ch + "px" });
  161. var canvas = document.createElement("canvas");
  162. canvas.width = Math.round(cw * dpr);
  163. canvas.height = Math.round(ch * dpr);
  164. canvas.style.width = cw + "px";
  165. canvas.style.height = ch + "px";
  166. $wrap.append(canvas);
  167. $b.append($wrap);
  168. $b.append('<div class="of-dim">Draw with the mouse, a pen or a finger. The drawing is inserted as a picture, trimmed to what you drew.</div>');
  169. var ctx = canvas.getContext("2d");
  170. function redraw() {
  171. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  172. ctx.clearRect(0, 0, cw, ch);
  173. strokes.forEach(function (s) { drawStroke(ctx, s); });
  174. if (cur) drawStroke(ctx, cur);
  175. }
  176. function syncBar() {
  177. $pens.find(".of-sketch-pen").removeClass("active");
  178. if (penId && !tool.eraser) $pens.find('[data-pen="' + penId + '"]').addClass("active");
  179. $eraser.toggleClass("active", tool.eraser);
  180. $wrap.toggleClass("erasing", tool.eraser);
  181. $undo.prop("disabled", hpos === 0);
  182. $redo.prop("disabled", hpos >= history.length - 1);
  183. $clear.prop("disabled", strokes.length === 0);
  184. }
  185. function remember() {
  186. history = history.slice(0, hpos + 1);
  187. history.push(strokes.slice());
  188. hpos = history.length - 1;
  189. syncBar();
  190. }
  191. $undo.on("click", function () {
  192. if (hpos === 0) return;
  193. hpos--;
  194. strokes = history[hpos].slice();
  195. redraw();
  196. syncBar();
  197. });
  198. $redo.on("click", function () {
  199. if (hpos >= history.length - 1) return;
  200. hpos++;
  201. strokes = history[hpos].slice();
  202. redraw();
  203. syncBar();
  204. });
  205. $clear.on("click", function () {
  206. if (!strokes.length) return;
  207. strokes = [];
  208. redraw();
  209. remember();
  210. });
  211. function at(e) {
  212. var r = canvas.getBoundingClientRect();
  213. return [(e.clientX - r.left) * cw / r.width, (e.clientY - r.top) * ch / r.height];
  214. }
  215. var erasedAny = false;
  216. function eraseAt(q) {
  217. var keep = strokes.filter(function (s) { return !hits(s, q[0], q[1], 6); });
  218. if (keep.length !== strokes.length) {
  219. strokes = keep;
  220. erasedAny = true;
  221. redraw();
  222. }
  223. }
  224. canvas.addEventListener("pointerdown", function (e) {
  225. if (e.button !== undefined && e.button !== 0 && e.pointerType === "mouse") return;
  226. e.preventDefault();
  227. try { canvas.setPointerCapture(e.pointerId); } catch (err) { }
  228. var q = at(e);
  229. if (tool.eraser || e.button === 5) {
  230. erasedAny = false;
  231. cur = { erasing: true, pts: [] };
  232. eraseAt(q);
  233. return;
  234. }
  235. cur = { kind: tool.kind, color: tool.color, width: tool.width, pts: [q] };
  236. redraw();
  237. });
  238. canvas.addEventListener("pointermove", function (e) {
  239. if (!cur) return;
  240. e.preventDefault();
  241. var list = (e.getCoalescedEvents && e.getCoalescedEvents()) || [e];
  242. if (!list.length) list = [e];
  243. if (cur.erasing) {
  244. list.forEach(function (ev) { eraseAt(at(ev)); });
  245. return;
  246. }
  247. list.forEach(function (ev) {
  248. var q = at(ev), last = cur.pts[cur.pts.length - 1];
  249. var dx = q[0] - last[0], dy = q[1] - last[1];
  250. if (dx * dx + dy * dy >= 0.6) cur.pts.push(q);
  251. });
  252. redraw();
  253. });
  254. var finish = function () {
  255. if (!cur) return;
  256. if (cur.erasing) {
  257. cur = null;
  258. if (erasedAny) remember();
  259. return;
  260. }
  261. strokes.push(cur);
  262. cur = null;
  263. redraw();
  264. remember();
  265. };
  266. canvas.addEventListener("pointerup", finish);
  267. canvas.addEventListener("pointercancel", finish);
  268. function insert(close) {
  269. var bb = bounds(strokes);
  270. if (!bb) {
  271. OfficeApp.toast("Draw something first", "error");
  272. return;
  273. }
  274. var x1 = Math.max(0, Math.floor(bb.x1)), y1 = Math.max(0, Math.floor(bb.y1));
  275. var w = Math.max(1, Math.ceil(Math.min(cw, bb.x2) - x1));
  276. var h = Math.max(1, Math.ceil(Math.min(ch, bb.y2) - y1));
  277. var S = 2;
  278. var out = document.createElement("canvas");
  279. out.width = w * S;
  280. out.height = h * S;
  281. var octx = out.getContext("2d");
  282. octx.setTransform(S, 0, 0, S, -x1 * S, -y1 * S);
  283. strokes.forEach(function (s) { drawStroke(octx, s); });
  284. out.toBlob(function (blob) {
  285. if (!blob) { OfficeApp.toast("The drawing could not be made into a picture", "error"); return; }
  286. close();
  287. if (o.onInsert) o.onInsert(blob, w, h);
  288. }, "image/png");
  289. }
  290. OfficeApp.dialog({
  291. title: o.title || "Drawing",
  292. body: $b,
  293. wide: true,
  294. dismissable: false,
  295. buttons: [
  296. { label: "Cancel" },
  297. { label: o.insertLabel || "Insert", primary: true, action: function (close) { insert(close); } }
  298. ]
  299. });
  300. syncBar();
  301. redraw();
  302. }
  303. return { open: open, PENS: PENS, penIcon: penIcon, penById: penById };
  304. })();