Ten kod ma prosty cel - przesuwa do samego dołu elementu canvas prostokąt o wymiarach 20x60 i w pewnym momencie go obraca o 90 stopni. Wydaje mi się, że wartości przekazane do translate() w metodzie rotate() są poprawne, ale oczywiści w js nic nie może być logiczne i oczywiste - kiedy obrócę prostokąt o 90 stopni ląduje on dwie swoje wysokości niżej, o 180 i przesuwa się do lewego marginesu canvas. Czy istnieje jakiś dobry sposób, żebym nie musiał za każdym razem w metodzie rotate() sprawdzać podanego kąta obrotu i obliczać właściwych wartości względem bieżącego kąta?
[javascript]
function GenericFigure(context) {
this.states = ["wait", "moving", "rotating", "stop"];
this.state = this.states[0];
this.ctx = context;
this.sqrW = this.sqrH = 20;
this.ctxW = 200;
this.ctxH = 350;
this.colorsO = {
red : "#ee1515",
green : "#45d137",
blue : "#17a3f3",
orange : "#ff910f",
purple : "#680077"
};
this.colorsA = ["#ee1515", "#45d137", "#17a3f3", "#ff910f", "#680077"];
this.pickColor = function() {
var num = Math.floor(Math.random() * 5);
return this.colorsA[num];
}
}
function Rectangle(context) {
this.inheritFrom = GenericFigure;
this.inheritFrom(context);
this.width = this.sqrW;
this.height = this.sqrH * 3;
this.x = this.ctxW / 2;
this.y = 0;
this.rotation = -1;
this.setRotation = function(angle) {
this.rotation = angle;
}
this.rotate = function() {
this.ctx.clearRect(0, 0, this.ctxW, this.ctxH);
this.ctx.translate(this.x + this.width / 2, this.y + this.height / 2);
this.ctx.rotate(this.rotation * Math.PI / 180);
this.ctx.fillRect(this.ctxW / 2, 0, this.width, this.height);
this.ctx.restore();
}
this.moveDown = function() {
this.y += 20;
this.ctx.restore();
this.ctx.clearRect(0, 0, this.ctxW, this.ctxH);
this.ctx.fillRect(this.x, this.y, this.width, this.height);
this.ctx.save();
if(this.rotation > -1) {
this.rotate();
}
l("A");
}
this.draw = function() {
this.ctx.fillStyle = this.pickColor();
this.ctx.save();
this.ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
//a tak można wywołać:
var ctx = document.getElementById("game").getContext("2d");
var rect = new Rectangle(ctx);
rect.draw();
var inte = setInterval(function(){if(rect.y >= rect.ctxH - rect.height){clearInterval(inte);return;}if(rect.y == 60) rect.setRotation(90);rect.moveDown();}, 500);
[/javascript]