代码有点多,但这里有一种技术可以用来绘制图像的剪辑版本。根据需要实施 -
现场示例
在每个timeupdate
:
- 画布被清除
- 绘制了白色底部图像(您可以根据需要缩放这些图像)
- 计算进度(currentTime / duration)
- 红顶图像是使用裁剪参数绘制的:
IE。
ctx.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
完整的示例代码(由于 API 的使用不得不替换音乐) -
var imgBg = new Image(),
imgFg = new Image(),
count = 2;
imgBg.onload = imgFg.onload = init;
imgBg.src = "http://i.imgur.com/hRHH9VO.png";
imgFg.src = "http://i.imgur.com/WoJggN0.png";
function init() {
if (--count) return; // makes sure both images are loaded
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d"),
audio = document.querySelector("audio");
canvas.width = imgBg.naturalWidth;
canvas.height = imgBg.naturalHeight;
render();
audio.volume = 0.5;
audio.addEventListener("timeupdate", render);
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(imgBg, 0, 0);
// calc progress
var pst = audio.currentTime / audio.duration;
// draw clipped version of top image
if (pst > 0) {
ctx.drawImage(imgFg, 0, 0, (canvas.width * pst)|0, canvas.height, // source
0, 0, (canvas.width * pst)|0, canvas.height); // dst
}
}
}
body {background:#ccc}
canvas {width:600px;height:auto}
<audio src="https://raw.githubusercontent.com/epistemex/free-music-for-test-and-demo/master/music/kf_colibris.mp3" controls></audio>
<canvas></canvas>