This repository has been archived by the owner on Apr 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathcanvaspaint.js
82 lines (68 loc) · 2.47 KB
/
canvaspaint.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
(function (window, document, Rx) {
Rx.DOM = { };
['mousemove', 'mouseup', 'mousedown', 'click'].forEach(function (name) {
Rx.DOM[name] = function (element, selector) {
return Rx.Observable.fromEvent(element, name, selector);
};
});
Rx.DOM.ready = function () {
return Rx.Observable.create(function (o) {
function handler() {
o.onNext();
o.onCompleted();
}
var added = false;
if (document.readyState === 'complete') {
handler();
} else {
document.addEventListener('DOMContentLoaded', handler, false);
added = true;
return Rx.Disposable.create(function () {
added && document.removeEventListener('DOMContentLoaded', handler, false);
});
}
}).take(1);
};
// Calcualte offset either layerX/Y or offsetX/Y
function getOffset(event) {
return {
offsetX: event.offsetX === undefined ? event.layerX : event.offsetX,
offsetY: event.offsetY === undefined ? event.layerY : event.offsetY
};
}
function intialize () {
var canvas = document.getElementById('tutorial');
var colorchart = document.querySelectorAll('#colorchart tr td');
var ctx = canvas.getContext('2d');
ctx.beginPath();
// Get mouse events
var mouseMoves = Rx.DOM.mousemove(canvas),
mouseDowns = Rx.DOM.mousedown(canvas),
mouseUps = Rx.DOM.mouseup(canvas);
// Get the table events
var colorValues = Rx.DOM.click(colorchart)
.tap(function () { ctx.beginPath(); })
.map(function (e) { return e.target.bgColor; })
.startWith('#000000');
// Calculate difference between two mouse moves
var mouseDiffs = mouseMoves.zip(mouseMoves.skip(1), function (x, y) {
return { first: getOffset(x), second: getOffset(y) };
});
// Get merge together both mouse up and mouse down
var mouseButton = mouseDowns.map(true)
.merge(mouseUps.map(false));
// Paint if the mouse is down
var paint = mouseButton.flatMapLatest(function (down) { return down ? mouseDiffs : Rx.Observable.never(); })
.combineLatest(colorValues, function (pos, color) {
return { pos : pos, color: color };
});
// Update the canvas
paint.subscribe(function (x) {
ctx.strokeStyle = x.color;
ctx.moveTo(x.pos.first.offsetX, x.pos.first.offsetY);
ctx.lineTo(x.pos.second.offsetX, x.pos.second.offsetY);
ctx.stroke();
});
}
Rx.DOM.ready().subscribe(intialize);
}(window, document, Rx));