1

I use the following function to scale and translate and when browser windows is resized. However, I want to save the aspect ratio (now some parts of video are cut off) when size of window is changed, just like media players handle window resizing.

/**
 * This function is called when 'resize' event occur, it simply changes the way 
 * <canvas> and <video> are displayed by browser using few CSS3 techniques.
 * @return none
 */
    function resize() {

        var w = 0;
        var h = 0;

        if (!window.innerWidth) {
            if (!(document.documentElement.clientWidth == 0)) {
                w = document.documentElement.clientWidth;
                h = document.documentElement.clientHeight;
            } else {
                w = document.body.clientWidth;
                h = document.body.clientHeight;
            }
        } else {
            w = window.innerWidth;
            h = window.innerHeight;
        }

        var cw = w;
        var ch = h;

        var aspect = videoWidth / videoHeight;

        if (w / h > aspect) {
            ch = cw / aspect;
        } else {
            cw = ch * aspect;
        }

        scalew = cw / videoWidth;
        scaleh = ch / videoHeight;

        dx = Math.round((w - cw) / 2);
        dy = Math.round((h - ch) / 2);

        var translateXForm = "translate(" + dx + "px," + dy + "px)";
        var scaleXForm = "scale(" + scalew + "," + scaleh + ")";
        var transform = translateXForm + " " + scaleXForm; 
        var style =
        "-webkit-transform:" + transform + ";" +
        "-moz-transform:" + transform + ";" +
        "-ms-transform:" + transform + ";" +
        "-o-transform:" + transform + ";" +
        "transform:" + transform;

        canvas.setAttribute("style", style);
        video.setAttribute("style", style);

    }
RaphaelDDL
  • 4,452
  • 2
  • 32
  • 56
Kristian Vitozev
  • 5,791
  • 6
  • 36
  • 56

1 Answers1

1

Doing it with JavaScript isn't necessary, we can achieve this using pure CSS!

Simply set the following styles to the video tag:

video {
    height: auto;
    width: 100%;
}

This will keep your aspect ratio when the window is resized

DEMO

Andy
  • 14,427
  • 3
  • 52
  • 76
  • Thanks! It works fine for – Kristian Vitozev Apr 26 '13 at 13:50