如何旋转形状?

4

目前为止我得到的:

我可以使用一些简单的语法在画布中绘制形状:

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
我注意到,将任何形状旋转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>

1个回答

3

将其转换为一个二维数组,旋转(不是转置)该数组,然后再转换回去。

编辑:感谢meowgoesthedog的指正,transpose并不是我所想的意思。

var rotate = array => array[0].map( (col, i) => array.map(row => row[i]).reverse() );
var decode = str => str.split('n').map( s => s.split('') )
var encode = arr => arr.map( a => a.join('') ).join('n')

encode( rotate( decode( '01n00' ) ) )

@jonas00 你在完全否定他的代码之前,甚至没有试着测试一下吗?str.spilt只是一个笔误,这不是显而易见的吗? - meowgoesthedog
好像确实是这样。无论如何,可能的解决方法是反转每一行;这将把转置(反射)转换为90度旋转。即 var encode = arr => arr.map( a => a.reverse().join('')).join('n')。反转行的顺序将向相反方向旋转90度。 - meowgoesthedog
@jonas00,它可以工作了,形状被顺时针旋转了90度。多次调用“rotate”以到达其他位置。 - Ben West

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接