题
Is there a way to get Stylus calculate the square root of x
?
You know, like JavaScript's Math.sqrt(x)
does.
I am creating a diamond that should be centered on it's origin. the following code am i using at the moment:
vendor(prop, args...)
-webkit-{prop} args
-moz-{prop} args
-o-{prop} args
-ms-{prop} args
rotate(r)
vendor('transform', unquote('rotate('+r+')'))
rotate r
.diamond
display block
width 7ex
height @width
line-height @height
rotate(-45deg)
/* calc offset of a rotated square
* @width * @width = $offsetX * $offsetX + $offsetY * $offsetY
* @width * @width = ( $offset * $offset ) * 2 // for a square: $offsetX= $offsetY
* ( @width * @width ) / 2 = ( $offset * $offset )
* sqrt(( @width * @width ) / 2) = $offset
* @width * sqrt(2) = $offset
*/
$offset = @width / 1.41421356237 // =sqrt( 2 )
margin (- $offset) 0em 0ex (- $offset ) // center the diamond on its origin
padding 0ex 0em
background-color red
as you can see, i managed to work it out without actually calculating the square root, but using a constant value instead.
But when I looked at the Built-in Functions of Stylus, I was unable to find any method to calculate the square root.
Is there any way to get stylus calculate the square root of x
?
Of cause the best would be to have some nice functions like LESS has built in.
解决方案
As answered there you can use the built-in math
function for this, so the custom sqrt
could look better:
sqrt(x)
return math(x, 'sqrt')
其他提示
you can use this code:
sqrt(x)
if x == 0
result = 0
else
result = 4
for i in (0..10)
result = ((result + (x / result)) / 2)
Demo on codepen: http://cdpn.io/jcnLF