k200338 Mahad Hameed
k200338 Mahad Hameed

Reputation: 47

Cant set origin for an element in JavaScript

I am making a simple game in js which consists of a grid and some cellsenter image description here

This is what it currently looks like and it works perfectly. The thing is that while making this I set the margin to 0 but I would like to move the canvas to center. To do that, I got the margin from this function

var test = document.querySelector('.test');
var left_margin = window.getComputedStyle(test).getPropertyValue("margin- 
    left "); // returns margin e.g. '655px'
    left_margin = left_margin.match(/\d+/);
                       

Then I made some changes in the whole thing to account for this offset but for some reason when I try to add the offset to the x-axis, it returns NaN. To make sure there wasnt some problem I performed some basic mathematical operations on this value and they worked. Can someone tell me what is going on with this? and also, is there a simple way to just redefine the origin for an element(a canvas in my case), to avoid this hassle?

Edit: I dont understand this. When i simply do var a = blockWidth + 0;The game doesnt start and then do console.log(a) this also return NaN. and i get**(Uncaught TypeError: Cannot set property 'strokeStyle' of undefined)**

function grid(){
    var a = blockWidth + left_margin;
    var b = blockHeight;
    while (a != widthWin){
        drawLine(a, 0, a, heightWin, 1, 'gray');
        a += blockWidth;
    }
    while (b != heightWin){
        drawLine(left_margin, b, widthWin+left_margin, b, 1, 'gray');
        b += blockHeight;
    }
}

Upvotes: 0

Views: 104

Answers (1)

Dario
Dario

Reputation: 6280

What you get with

left_margin = left_margin.match(/\d+/);

is an array ["655"] not an int as you are assuming.

Therefore, you need to access its first element and parse it to a number before using it for doing any math:

left_margin = parseInt(left_margin.match(/\d+/)[0]);

Upvotes: 1

Related Questions