【问题标题】:How to calc square root in stylus如何在手写笔中计算平方根
【发布时间】:2014-01-28 18:41:12
【问题描述】:

有没有办法让 Stylus 计算 x 的平方根?
你知道,就像 JavaScript 的 Math.sqrt(x) 一样。

我正在创建一个应该以它的原点为中心的钻石。我目前正在使用以下代码:

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

如您所见,我设法在没有实际计算平方根的情况下解决了这个问题,而是使用了一个常数值。 但是当我查看Built-in Functions of Stylus 时,我找不到任何计算平方根的方法。

有什么方法可以让手写笔计算x 的平方根吗?
当然最好有一些不错的函数,比如LESS has built in.

【问题讨论】:

标签: stylus


【解决方案1】:

您可以使用此代码:

sqrt(x)
  if x == 0
    result = 0
  else
    result = 4
    for i in (0..10)
      result = ((result + (x / result)) / 2)

codepen 上的演示:http://cdpn.io/jcnLF

【讨论】:

    【解决方案2】:

    作为answered there,你可以使用内置的math函数,这样自定义的sqrt会更好看:

    sqrt(x)
      return math(x, 'sqrt')
    

    【讨论】:

    • 你可以将多个参数传递给数学函数吗?我正在尝试做powgist.github.com/corysimmons/9d4c482397317bb6378a,但它出错了。我只需要遍历空格分隔的 vals 吗?
    • Stylus 有 pow operator 开箱即用:4 ** 3 :) 没有其他数学方法在数学函数中需要更多的参数。
    • 大声笑,我太愚蠢了。我完全了解指数运算符。写这篇评论的时候太累了。再次感谢木津。 =)
    猜你喜欢
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 2021-01-04
    • 1970-01-01
    • 2021-08-03
    • 2021-05-08
    相关资源
    最近更新 更多