Что у меня так далеко:
Я могу рисовать фигуры на холсте, используя простой синтаксис:
let shape = "10n10" // example shapeSyntax (*)
shapeSyntax: "1" == "colored area"
"0" == "blank area"
"n" == "new line"
* So creating a simple line (width = 4, height = 1) is possible using the syntax "1111"
* Creating a square (width = 2, height = 2) is possible using the syntax "11n11" (n stands for new line)
* Creating a stair -shape would be possible using the syntax "001n011n111"
Пока все работает очень хорошо. Итак, я добавил код, чтобы вы могли взглянуть на него:
Что бы я хотел получить:
Я бы хотел разработать функцию rotate(degree)
, которая могла бы вращать синтаксис (, а не только элемент canvas или что-то еще !!! ) любой формы вокруг [90, 180, 270]
градусов.
Таким образом, поворот строки с синтаксисом «1111» примерно на 90deg
должен получить «1n1n1n1»:
rotate("1111", 90) // == "1n1n1n1"
Пожалуйста, посмотрите на это изображение, я уверен, что оно поможет понять:
![img](https://i.stack.imgur.com/UzKy6.png)
Что я заметил, так это то, что при повороте любой формы на 180 градусов синтаксис можно просто изменить, прочитав его в обратном направлении: "1011" gets "1101"
. Но как я могу получить синтаксис от 0->90deg
? Я понятия не имел, как будет полезна любая помощь, как решить эту проблему. Заранее спасибо.
// This is what I've got
// The 4 shapes where
// "1" == "colored area"
// "0" == "blank area"
// "n" == "new line"
let shapeA = "1111"
let shapeB = "10n11"
let shapeC = "111n011"
let shapeD = "00111n11100"
// This is the function to draw the shapes using *canvas*
let drawShape = function(shape, offset) {
shape = shape.split("n");
let shapeHeight = shape.length,
shapeWidth = shape[0].length;
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = canvas.height = 300;
ctx.fillStyle=["red", "green", "blue", "gray", "magenta", "orange", "yellow"][Math.round(Math.random()*6)];
for (let y=0; y<shapeHeight; y++) {
for (let x=0; x<shapeWidth; x++) {
if (shape[y][x] === "1")
ctx.fillRect(x*20, y*20, 20, 20);
}
}
canvas.style.position = "absolute";
canvas.style.left = offset + "%";
document.getElementById("element").append(canvas)
}
// This is how I'm able to call the function (the second parameter is for the offset of the position)
drawShape(shapeA, 0);
drawShape(shapeB, 20);
drawShape(shapeC, 40);
drawShape(shapeD, 60);
input {
position: absolute;
top: 50%;
z-index: 4
}
<input type="text" oninput="document.getElementById('element').innerHTML = ''; drawShape(this.value, 10)" placeholder="input shape syntax"/>
<div id="element"></div>