Search code examples
javascripthtmlhtml5-canvasdrawimagerangeslider

Binding a Range Slider to Image Sequence


I want to show a timelapse video but have it with a Range slider so the user can drag it back and forth. I've tried with a video but I don't like the loading effect as you scroll. I also exported the video as images and binded it to the range slider. First question is, isn't there any plugins or applications out there that do this? Maybe i'm searching the wrong terms. Second is an image sequence the best way to do this? In my code below I can get it to partially work, but I can't figure out how to resize the image, and it's way to big for the canvas.

<style>
  canvas {
    height: 650px;
    width: 1000px;
    border: 1px solid black;
  }
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 
</script>
<canvas id="canvas" height="650px" width="1000px"></canvas>
<br>
<input id="my-input" type="range" min="1" max="50" value="1">
<script type="text/javascript">
    var canvas = document.getElementById("canvas");
    canvas.height = window.innerHeight;
    canvas.width = window.innerWidth;

    var totalImages = 50;
    var videoFrames = [];
    for (var i = 1; i <= totalImages; i++) {
      var videoFrame = new Image;
      var videoFrameUrl = 'http://dacwebdesign.com/testing/images/timelapse-' + i + '.jpg';

      videoFrame.src = videoFrameUrl;
      videoFrames.push(videoFrame);
    }

  $("#my-input").on("input", function(event) {
    var currentImage = videoFrames[event.target.value - 1];
    var context = canvas.getContext("2d");
    context.drawImage(currentImage, 0, 0);
      });
</script>

Solution

  • You can resize the images to fit your canvas with:

    var currentImage = videoFrames[event.target.value - 1];
    var context = canvas.getContext("2d");
    var dstWidth = canvas.width;
    var dstHeight = canvas.height;
    var srcWidth = currentImage.naturalWidth;
    var srcHeight = currentImage.naturalHeight;
    context.drawImage(currentImage, 0, 0, srcWidth, srcHeight, 0, 0, dstWidth, dstHeight);
    

    That does not take into account aspect ratios, so if your canvas has a different aspect ratio to your images, it will appear distorted.