响应式HTML5视频+画布 [英] Responsive HTML5 Video + Canvas

查看:257
本文介绍了响应式HTML5视频+画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下函数进行缩放和翻译,以及调整浏览器窗口大小时。但是,当窗口大小改变时,我想保存宽高比(现在视频的一些部分被切掉),就像媒体播放器处理窗口大小调整一样。

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);

    }


推荐答案

没有必要使用JavaScript,我们可以使用纯CSS!

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

这篇关于响应式HTML5视频+画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆