How to calc square root in stylus

给你一囗甜甜゛ 提交于 2019-12-14 01:33:17

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/21033346/how-to-calc-square-root-in-stylus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!