使用Canvas调整覆盖图像的大小

时间:2015-04-23 16:17:50

标签: javascript html5 canvas html5-canvas html5-audio

我有一个音频波形,两个图像的页面是白色层和红色层。白色图层是调整大小的尺寸,但是当歌曲播放时,我无法使红色图层的大小正确。我不明白为什么。

以下是我正在使用的代码,也是一个小提琴

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 = 750;
  canvas.height = 120;

  render();

  audio.volume = 0.5;
  audio.addEventListener("timeupdate", render);

  function render() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(imgBg, 0, 0, canvas.width, canvas.height);

    // 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
    }
  }
}

https://jsfiddle.net/tallgirltaadaa/pxezgj99/

1 个答案:

答案 0 :(得分:1)

只需更改drawImage()中的来源尺寸,即可将图片尺寸用作来源:

ctx.drawImage(imgFg, 0, 0, imgFg.width * pst, imgFg.height,     // src
                     0, 0, canvas.width * pst, canvas.height);  // dst

由于此处的图像大于目标画布,您必须使用源大小作为基础,然后将其全部缩放到目标。

<强> Modified fiddle