Hackrrr
Hackrrr

Reputation: 338

JavaScript: Rotating object in canvas

last three weeks I was creating a canvas engine and last week I was trying to solve one problem with rotating an object in canvas. I had tried many solutions, but unsuccessfully. I most cases, code was rotate whole content of canvas or it displayed nothing (as it is now (but if you remove .save() and .restore(), everything will be rotate)). I hope that this avoids big changes in code because it is my biggest code that I write (and I don't want to do many changes). The code snippet is bellow and thanks for any help. (If you want to see whole code, you can go here)

//Functions.js File
function degToRad(int) {
    return int * Math.PI / 180;
}

//Init.js File
var fps = 0;
var objects = new Array();
var ctx_real = {
    context: undefined,
    width: 0,
    height: 0,
    init: function () {
        this.context = this.DOM.getContext("2d");
        this.width = this.DOM.width;
        this.height = this.DOM.height;
    },
    clear: function () {
        this.context.clearRect(0, 0, this.width, this.height);
    }
};
const proXy_ctx = {
    get: function (target, prop) {
        return target.hasOwnProperty(prop) ? target[prop] : ctx_real.context; //=> ctx.SomeAtributeThatNotExists = ctx.context
    }
};
const ctx = new Proxy(ctx_real, proXy_ctx);

function init() {
    ctx.DOM = document.getElementById("ctx");
    ctx.init();
    setLayout("Game");
    setLayout("Test2");
    setInterval(frameUpdate, 1);
}

//Script.js File
async function frameUpdate() {
    ctx.clear();
    clearObjects = false;
    for (var tmp0 = 0 in objects) {
        var object = objects[tmp0];
        var id = object[0];
        var type = object[1];
        var x = object[2];
        var y = object[3];
        var color = object[4];
        ctx.context.strokeStyle = color;
        ctx.context.fillStyle = color;
        var arg0 = object[5];
        var arg1 = object[6];
        var arg3 = object[8];
        var arg4 = object[9];
        switch (type) {
            case "Rct":
                var translateX = x + (arg0 / 2);
                var translateY = y + (arg1 / 2);
                if (typeof arg3 == "number" && arg3 != 0) {
                    ctx.context.save();
                    ctx.context.translate(translateX, translateY);
                    ctx.context.rotate(degToRad(arg3));
                }
                if (arg4) {
                    ctx.context.fillRect(x, y, arg0, arg1);
                } else {
                    ctx.context.strokeRect(x, y, arg0, arg1);
                }
                if (typeof arg3 == "number") {
                    ctx.context.restore();
                }
                break;
        }
    }
    if (clearObjects) {
        objects = objects.filter(Boolean);
    }
    fps++;
    setTimeout(function () { fps--; }, 1000);
    ctx.context.fillStyle = "black";
    ctx.context.font = "10px Verdana";
    ctx.context.fillText(fps, 10, 10);
}

function setLayout(layoutName) {
    switch (layoutName) {
        case "Game":
            createObject(["SomeId", "Rct", 0, ctx.height - 30, "green", ctx.width, 30, , , true]);
            createObject(["SomeId", "Rct", 0, ctx.height - 30, "#402a25", ctx.width, 3, , , true]);
            break;
        case "Test2":
            createObject(["SomeRotatedEl", "Rct", ctx.width / 2, ctx.height / 2, "red", 50, 50, , 90, true]);
            break;
    }
}

function createObject(object) {
    objects.push(object);
}
html,
body,
canvas {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
  overflow-x: hidden;
  overflow-y: hidden;
}
<!DOCTYPE html>
<html>
<body onLoad="init()">
  <canvas id="ctx">You can simple download e.g. Chrome or what?!!!</canvas>
</body>
</html>

Upvotes: 0

Views: 180

Answers (1)

Wlodzislav K.
Wlodzislav K.

Reputation: 404

You can't draw rotated object on the canvas without "rotating" all the canvas.

Unfortunately that's how canvas works. Think about it that way:

You could only draw at single point in space {x:0,y:0} and the canvas is right below that point like a physical piece of paper.

Then if you want to draw at {x:0,y:10} you move all the canvas 10px up, so now the point you are drawing from became {x:0,y:10} if you count from the top/left of the canvas, but it's {x:0,y:0} for drawing.

// red rect at {x:0,y:40}
ctx.fillStyle = "rgba(255,0,0,0.3)";
ctx.translate(0, 40) // means that {x:0,y:10} "is new" {x:0,y:0}
ctx.fillRect(0, 0, 40, 20);

If you want to rotate, you rotate canvas, so that the thing you want to draw will appear as it's rotated:

// reset all transformations
ctx.setTransform(1, 0, 0, 1, 0, 0);
// green rect at {x:0,y:0} rotated 45deg
ctx.fillStyle = "rgba(0,255,0,0.3)";
ctx.rotate(45 * Math.PI / 180);
ctx.fillRect(0, 0, 40, 20);

But it's rotated around its top/left corner. I guess that's you problem?

To rotate object properly(with center as the rotation axis) you need to place canvas so that center of the object became {x:0,y:0}. Then rotate and draw the object so that its center is at {x:0,y:0}, for most objects it means that you draw them at {x:-width/2,y:-height/2}.

For example if you want blue rect at {x:50,y:50} rotated 45deg with {width:40,height:20}

// reset all transformations
ctx.setTransform(1, 0, 0, 1, 0, 0);

// blue rect at {x:50,y:50} rotated 45deg
var rectWidth = 40;
var rectHeight = 20;
ctx.fillStyle = "rgba(0,0,255,0.3)";
ctx.translate(50, 50);
ctx.rotate(45 * Math.PI / 180);
ctx.fillRect(-rectWidth/2, -rectHeight/2, rectWidth, rectHeight);

See for complete example: https://codepen.io/anon/pen/QYGXzp?editors=0010

Upvotes: 1

Related Questions