繁体   English   中英

如何旋转形状?

[英]How to rotate shape?

到目前为止我得到了什么:

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

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" 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> 

转换为2D数组,旋转 (转置) 并转换回来。

编辑:谢谢meowgoesthedog,转置并不意味着我的意思。

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' ) ) )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM