// ClockMorph: A simple analog clock
Morph.subclass(“ClockMorph”, {
defaultBorderWidth: 2,
type: "ClockMorph",
// Constructor
initialize: function($super, position, radius) {
$super(position.asRectangle().expandBy(radius), "ellipse");
this.openForDragAndDrop = false; // Do not handle drag-and-drop requests
this.makeNewFace(); // Construct the clock face
return this;
},
// Construct a new clock face
makeNewFace: function() {
var bnds = this.shape.bounds();
var radius = bnds.width/3;
var labels = [];
var fontSize = Math.max(Math.floor(0.04 * (bnds.width + bnds.height)),4);
var labelSize = fontSize; // room to center with default inset
// Add Roman numerals to the clock
for (var i = 0; i < 12; i++) {
var labelPosition = bnds.center().addPt(Point.polar(radius*0.85,
((i-3)/12)*Math.PI*2)).addXY(labelSize, 0);
var label = new TextMorph(pt(0,0).extent(pt(labelSize*3,labelSize)),
['XII','I','II','III','IV','V','VI','VII','VIII','IX','X','XI'][i]);
label.setWrapStyle(WrapStyle.SHRINK);
label.setFontSize(fontSize);
label.setInset(pt(0,0));
label.setBorderWidth(0);
label.setFill(null);
label.align(label.bounds().center(),labelPosition.addXY(-2,1));
this.addMorph(label);
}
// Add clock hands
this.addMorph(this.hourHand = Morph.makeLine([pt(0,0),pt(0,-radius*0.5)],4,Color.blue));
this.addMorph(this.minuteHand = Morph.makeLine([pt(0,0),pt(0,-radius*0.7)],3,Color.blue));
this.addMorph(this.secondHand = Morph.makeLine([pt(0,0),pt(0,-radius*0.75)],2,Color.red));
this.setHands();
this.changed();
},
// Set clock hand angles based on current time
setHands: function() {
var now = new Date();
var second = now.getSeconds();
var minute = now.getMinutes() + second/60;
var hour = now.getHours() + minute/60;
this.hourHand.setRotation(hour/12*2*Math.PI);
this.minuteHand.setRotation(minute/60*2*Math.PI);
this.secondHand.setRotation(second/60*2*Math.PI);
},
// Will be called when the ClockMorph is placed in a world
startSteppingScripts: function() {
this.startStepping(1000, "setHands"); // once per second
}
});