目前为止我得到的:
我可以使用一些简单的语法在画布中绘制形状:
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)
,它能够使任何形状的语法(不仅仅是画布元素或其他东西!!!)在[90, 180, 270]
度周围旋转。
因此,将语法为“1111”的线条旋转90deg
应该得到“1n1n1n1”:
rotate("1111", 90) // == "1n1n1n1"
请看这张图片,我相信它会帮助你理解:
![img](https://istack.dev59.com/UzKy6.webp)
我注意到,将任何形状旋转180度,语法只需反向阅读:
"1011"变成了"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>
str.spilt
只是一个笔误,这不是显而易见的吗? - meowgoesthedogvar encode = arr => arr.map( a => a.reverse().join('')).join('n')
。反转行的顺序将向相反方向旋转90度。 - meowgoesthedog