So, I have an array like this:
var my_array = [
'00000000000000000',
'00000111111110000',
'00000111111110000',
'00000111111110000',
'00000111111110000',
'00000111111110000',
'00000000000000000'
]
...and I'd like to get a function that is able to rotate the array (2d matrix above) by a certain angle (e.g 30°) around a certain point (x/y center of array : e.g X: 8, Y: 3).
So the result for 30° should maybe look like this: (Array is not that exact, just an example...)
var rotated_array = [
"00000000000000000",
"00000000001100000",
"00000000111110000",
"00000001111111000",
"00000111111111100",
"00000111111111000",
"00000011111100000",
"00000001110000000",
"00000000100000000",
"00000000000000000"
]
I've already created a function you can find below, but the function has some errors (The rotated matrix is missing some points and looks kind of destroyed --> You can test it on your own below).
I hope somebody can help me fixing my code, so however...
Thanks in advance, jonas.
BTW: I have marked all 'new' points which were never used with a '*'-character, afterwards I will use zeros instead!
var my_array = [
'00000000000000000000000',
'00000000000000000000000',
'00000000000000000000000',
'00000000000000000000000',
'00000011111111000000000',
'00000011111111000000000',
'00000011111111000000000',
'00000011111111000000000',
'00000011111111000000000',
'00000000000000000000000',
'00000000000000000000000',
'00000000000000000000000',
'00000000000000000000000'
]
Array.prototype.rotate_matrix = function(angle, cx, cy) {
function generate_matrix(rows,cols,value){
var arr = [];
for (var i=0; i < rows; i++) {
arr.push([]);arr[i].push(new Array(cols));
for (var j=0; j < cols; j++) arr[i][j] = value;
}; return arr;
}
var radians = (Math.PI / 180) * angle;
var array = generate_matrix(this.length, this[0].length, '*')
for (var i=0; i<this.length; i++) {
for (var j=0; j<this[i].length;j++) {
var character = this[i][j],
cos = Math.cos(radians),
sin = Math.sin(radians),
newx = Math.round((cos * (j - cx)) + (sin * (i - cy)) + cx) < this[i].length ? Math.round((cos * (j - cx)) + (sin * (i - cy)) + cx) : -1,
newy = Math.round((cos * (i - cy)) - (sin * (j - cx)) + cy) < this[i].length ? Math.round((cos * (i - cy)) - (sin * (j - cx)) + cy) : 1;
try {array[newy][newx]=character;}
catch(e) {
array[i][j] = character
}
}
}
array = array.map(a => [a.join('')])
return array.concat.apply([],array);
}
console.log(my_array.rotate_matrix(30,(my_array[0].length/2),(my_array.length/2)))