forked from robdodson/JavaScript-Design-Patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
62 lines (56 loc) · 1.42 KB
/
main.js
File metadata and controls
62 lines (56 loc) · 1.42 KB
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
$(function() {
var $canvas, context,
offset, offsetLeft, offsetTop,
isDrawing,
brush, brushes;
$canvas = $('#painter');
context = $canvas[0].getContext('2d');
// Find the canvas offset so we can get accurate
// mouse positions for our shapes
offset = $canvas.offset();
offsetLeft = offset.left;
offsetTop = offset.top;
// Set the initial state
isDrawing = false;
// Define our brush strategy objects
brushes = {
outline: {
draw: function(e, context) {
context.strokeRect(e.pageX - offsetLeft, e.pageY - offsetTop, 10, 10);
}
},
square: {
draw: function(e, context) {
context.fillRect(e.pageX - offsetLeft, e.pageY - offsetTop, 10, 10);
}
},
circle: {
draw: function(e, context) {
context.arc(e.pageX - offsetLeft, e.pageY - offsetTop, 10, 0, Math.PI * 2);
context.fill();
}
}
};
brush = brushes.circle;
// Listen for mouse events on the canvas
$canvas
.on('mousedown', function() {
isDrawing = true;
})
.on('mouseup mouseleave', function() {
isDrawing = false;
})
.on('mousemove', function(e) {
if (isDrawing) {
// Defer drawing to a strategy object
brush.draw(e, context);
}
});
// Listen for when the user changes the selected brush
$('#btns button').on('click', function(e) {
// Grab the button's `data-brush` attribute
// and set that as our brush strategy
var brushType = $(this).data('brush');
brush = brushes[brushType];
});
});