【问题标题】:Calculate how many elements will fit on image when spaces are involved计算涉及空格时有多少元素适合图像
【发布时间】:2018-03-24 23:40:47
【问题描述】:

我需要渲染 Nx 像素的项目,它们之间有 N-1 空格 y 像素宽。

我需要计算屏幕上会显示多少项目。我正在做的是将一组振幅渲染为列。这是我没有空格的测试产品:

我首先计算可以容纳多少项目,然后重新采样原始数组以准确获得适合屏幕的值的数量。这与每列 5 个像素相同,您可以看到原始数组已被重新采样:

我现在使用的公式是no_items = Math.floor(canvasWidth/(barWidth+spaceWidth))

/**
 * Recalculates waveform data for given width of canvas
 * @param {number} canvasWidth Image width in pixels
 * @param {number} barWidth Width of waveform bars
 * @param {number} spaceWidth Width of spaces between bars
 * @returns {Uint8Array} recalculated bytes
 */
recalculateForWidth(canvasWidth, barWidth, spaceWidth) {
    const no_items = Math.floor(canvasWidth/(barWidth+spaceWidth))
    const result = new Uint8Array(no_items);
    // Resampling code follows
    ...
    return result;
}

但这显然假设数据末尾有一个额外的空间 - 它只是用项目宽度计算为条宽 + 空间宽度。

我想渲染最后没有空格的条,那么我如何计算有多少条适合空格但最后没有空格?

【问题讨论】:

    标签: javascript algorithm math html5-canvas dynamic-image-generation


    【解决方案1】:

    为简化起见,我们举一个小例子。假设您有 103 个像素,并且您想要 5 个像素宽的条形和 2 个像素之间的空间。 正如您所说,比空格多 1 个小节。您希望最后一个栏位于屏幕的末尾,因此将您的宽度缩小这个数量,即 98 像素。

    然后,宽度的其余部分将除以 bar-space 对,每对的总长度为 barWidth + spaceWidth。也就是说,你有 98/7 = 14 对。总共有 15 个小节。

    所以,你的公式应该是

    (canvasWidth - barWidth) / (barWidth + spaceWidth) + 1
    

    最后一个小节的 +1 是最后一个小节。

    希望能为您解决问题。

    【讨论】:

      【解决方案2】:

      您的总宽度将为:

      barWidth(NumberBars) + spaceWidth(NumberBars - 1) = TotalWidth
      

      扩展为:

      barWidth(NumberBars) + (spaceWidth)(NumberBars) - spaceWidth = TotalWidth
      

      向两边添加spaceWidth:

      barWidth(NumberBars) + spaceWidth(NumberBars) = TotalWidth + spaceWidth
      

      因子左侧:

      NumberBars(barWidth + spaceWidth) = TotalWidth + spaceWidth
      

      然后划分:

      NumberBars = (TotalWidth + spaceWidth) / (barWidth + spaceWidth)
      

      【讨论】:

      • 啊,高中数学,我没听懂。谢谢。
      猜你喜欢
      • 2013-12-13
      • 2020-06-04
      • 2015-03-29
      • 1970-01-01
      • 1970-01-01
      • 2019-10-01
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      相关资源
      最近更新 更多