-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhETlib_slider.js
More file actions
71 lines (65 loc) · 1.97 KB
/
PhETlib_slider.js
File metadata and controls
71 lines (65 loc) · 1.97 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
63
64
65
66
67
68
69
70
71
function roundTo3(x) {
return parseFloat(x).toFixed(3);
}
//Creates custom svg slider element
function slider(canvas, x, y, w, h, minVal, maxVal, label) {
var body = canvas.rect(x, y, w, h);
var handle = canvas.rect(x, y, (w/50), h);
var bodyX = body.attr('x');
var handleX = handle.attr('x');
var handleW = handle.attr('width');
var self = this;
self.val = roundTo3(minVal); //initial value to be changed when dragged
self.maxVal = roundTo3(maxVal);
self.handle = handle;
var disp = canvas.text((x + (w/2)), (y - 10), label + ': ' + self.val);
disp.attr('font-weight', 'bold');
body.attr({fill:'white'});
handle.attr({fill:'gray'});
body.node.className = 'slider';
canvas.text(x, (y - 7), minVal);
canvas.text((x + w), (y - 7), maxVal);
function updateDisplay() {
var handleX = handle.attr('x');
var bodyX = body.attr('x');
var barDist = (handleX) - bodyX;
var val = (barDist / w) * (maxVal - minVal) + minVal; //value based on position of slider bar
self.val = roundTo3(val);
if (handleX == bodyX) {
self.val = roundTo3(minVal);
}
else if ((handleX + handleW) == (bodyX + w)) {
self.val = roundTo3(maxVal);
}
disp.attr('text', label + ': ' +self.val);
}
//move slider bar with mouse
handle.drag(function(dx,dy,mx,my) { //on move
var newX = Math.min(bodyX + w - handleW, mx);
newX = Math.max(bodyX, newX);
this.attr({x:newX})
updateDisplay();
},
function() {}, //on start
function() {} //on end
);
//clicks on slider body bring slider bar to click position
body.drag(function(dx,dy,mx,my) {
var newX = Math.min(bodyX + w - handleW, mx);
newX = Math.max(bodyX, newX);
handle.attr({x:newX})
updateDisplay();
},
function() {},
function() {}
);
body.mousedown(function(event) {
var newX = Math.min(bodyX + w - handleW, event.clientX);
newX = Math.max(bodyX, newX);
handle.attr({x:newX})
updateDisplay();
});
//change cursor on mouseover
body.attr('cursor', 'pointer');
handle.attr('cursor', 'pointer');
}