所以我有已经在JS文件中绘制的音频文件的波形。它们是远程存储的(例如:http://www.example.com/file.js),它们会在THIS pastebin中看到后面吐出来。
我搜索了高低,但无法在浏览器中找到如何在div中渲染它。我猜它是用帆布吗?
如果有人能够向我展示一个如何运作的简单小提琴,或者指出一个解释它的资源,我会非常感激。
!EDIT!我附上了一张图片,告诉你它是如何渲染的(只有白条,当然还有背景图像)。
答案 0 :(得分:0)
您需要做的就是遍历数组。先决条件是:
以下是一个例子:
var step = 4, // 2 points for line, 2 for space
skip = 1, // only use every n. point
width = data.length * step / skip, // width of waveform
maxY = 0, // see below
i;
// find max height
for(i = 0; i < data.length; i += skip)
if (data[i] > maxY) maxY = data[i]; // store the highest value
// transform the canvas using scale factors. The -height is to flip the coordinate system
ctx.transform(c.width / width, 0, 0, -c.height / maxY, 0, c.height);
// now add each bar to the path
for(i = 0; i < data.length; i += skip)
ctx.rect(i * step, 0, 2, data[i]);
// rasterize all bars at one (black here, use fillStyle to set different color)
ctx.fill()
下面提供的工作示例 -
function plot(data) {
var c = document.querySelector("canvas"),
ctx = c.getContext("2d"),
step = 3, // 2 points for line, 1 for space
width = data.length * step,
maxY = 0,
i;
// find max height
for(var i = 0; i < data.length; i++)
if (data[i] > maxY) maxY = data[i];
ctx.transform(c.width / width, 0, 0, -c.height / maxY, 0, c.height); // scale horizontally and flip coordinate system
for(var i = 0; i < data.length; i++)
ctx.rect(i * step, 0, 2, data[i]);
ctx.fill()
}
plot([148,154,144,153,171,165,170,170,162,174,169,172,169,179,196,177,204,171,174,175,169,177,178,182,173,194,179,185,177,173,174,174,165,171,183,173,188,177,173,170,172,177,167,196,177,173,187,176,181,176,176,171,172,155,146,150,151,144,149,151,157,148,150,141,143,139,138,170,176,168,176,184,174,172,173,164,166,162,173,169,157,179,157,170,171,170,181,162,177,162,178,166,173,168,166,174,170,169,171,176,185,172,182,173,172,164,177,161,171,167,170,166,159,165,163,170,179,149,149,143,147,145,142,137,157,141,142,151,139,162,167,169,169,171,170,161,159,164,157,160,159,171,175,181,170,170,175,171,189,164,181,172,175,191,168,176,165,163,157,172,171,168,160,164,165,168,172,173,168,176,172,178,169,172,179,171,171,171,176,167,174,168,175,174,171,182,178,181,166,175,162,179,184,175,183,183,194,196,192,198,192,195,193,198,204,195,222,201,198,199,190,201,188,199,193,161,198,188,183,184,197,188,187,183,185,182,200,193,193,186,202,189,195,186,188,191,194,203,193,189,184,192,179,175,163,174,170,178,181,167,179,174,182,182,174,171,158,180,187,176,172,176,182,176,153,155,187,182,189,189,180,205,189,186,191,182,194,184,202]); // cut short for demo
<canvas width=640 height=50></canvas>