Skip to content

Instantly share code, notes, and snippets.

@tkojitu
Created June 10, 2012 04:12
Show Gist options
  • Save tkojitu/2903802 to your computer and use it in GitHub Desktop.
Save tkojitu/2903802 to your computer and use it in GitHub Desktop.
Draw and rotate a rect in JavaScript Canvas.
<html>
<head>
<script type="text/javascript">
var app = {
rect: {
x: 100,
y: 100,
w: 100,
h: 100,
a: 0
},
draw: function() {
var cv = document.getElementById("canvas");
var cx = cv.getContext("2d");
cx.save();
cx.clearRect(0, 0, cv.width, cv.height);
var c = this.getRectCenter();
cx.translate(c.x, c.y);
cx.rotate(Math.PI / (180.0 / this.rect.a));
var r = this.getRotatedRect();
cx.strokeRect(r.x, r.y, r.w, r.h);
cx.restore();
},
getRectCenter: function() {
return {
x: this.rect.x + this.rect.w / 2,
y: this.rect.y + this.rect.h / 2
};
},
getRotatedRect: function() {
return {
x: this.rect.w / -2,
y: this.rect.h / -2,
w: this.rect.w,
h: this.rect.h
};
},
moveH: function(n) {
this.rect.x += n;
this.draw();
},
moveV: function(n) {
this.rect.y += n;
this.draw();
},
rotate: function(n) {
this.rect.a += n;
this.draw();
},
onLeft: function() {
this.moveH(-5);
},
onRight: function() {
this.moveH(5);
},
onUp: function() {
this.moveV(-5);
},
onDown: function() {
this.moveV(5);
},
onCounterClockwise: function() {
this.rotate(-5);
},
onClockwise: function() {
this.rotate(5);
}
};
</script>
</head>
<body onload="app.draw();">
<p>
<input type="button" value="<" onclick="app.onLeft();">
<input type="button" value=">" onclick="app.onRight();">
<input type="button" value="Up" onclick="app.onUp();">
<input type="button" value="Dn" onclick="app.onDown();">
<input type="button" value="<<" onclick="app.onCounterClockwise();">
<input type="button" value=">>" onclick="app.onClockwise();">
</p>
<p>
<canvas id="canvas" width=640 height=480>
Canvas
</canvas>
</p>
<pre>
<script type="text/javascript">
</script>
</pre>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment