计算涉及空间时图像适合的元素数量

时间:2018-03-24 23:40:48

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

我需要呈现N像素宽的x项,其间N-1个空格y像素宽。

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

enter image description here

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

enter image description here

我现在使用的公式是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;
}

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

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

2 个答案:

答案 0 :(得分:2)

为了简化,我们举一个小例子。假设你有103个像素,你想要5像素宽的条和它们之间2像素的空格。 正如你所说,除了空格之外还有1个吧。您希望最后一个条位于屏幕的末尾,因此请将此宽度减少,即98px。

然后,宽度的其余部分将被成对的条形空间分割,每个条形空间的总长度为barWidth + spaceWidth。也就是说,你有98/7 = 14对。总共有15个酒吧。

所以,你的公式应该是

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

最后一个+1是最后一个栏。

希望能为你修复它。

答案 1 :(得分:1)

您的总宽度将是:

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)
相关问题