【问题标题】:Dynamically setting size of HTML5 canvas based on the mobile screen基于手机屏幕动态设置 HTML5 画布大小
【发布时间】:2014-04-02 16:56:11
【问题描述】:

我想为Phonegap制作一个移动网页,它由一个标题和一个上下文组成,上下文包含一个画布。 我想让画布填充 100% 的内容 div,并使内容 div 适合整个屏幕的 80%。

这是我目前的代码

<div id="mappage" data-role="page"> 
    <div id="maphead" data-role="header">
    I am the Header
    </div>
    <div id="mapcontext" data-role="context">
    <canvas id="map" style="background: black">
    </canvas>
    <script>
        map.onload = map.onrezise = function(){
            var canvas = document.getElementById("map");
            canvas.style.position = "fixed";
            canvas.setAttribute("width", map.innerWidth);
            canvas.setAttribute("height", map.innerHeight*0.8);
                    canvas.style.top = map.innerHeight * 0.2 ;
        }

    </script>
    </div>
</div>

我得到的只是黑色画布,没有应用新尺寸,也没有应用顶部样式。

提前感谢您的帮助。

【问题讨论】:

    标签: javascript css html cordova canvas


    【解决方案1】:

    首先,事件名称是

    调整大小

    其次,您必须将事件设置为窗口。例如

    window.addEventListener('resize', function() {
        var canvas = document.getElementById('map');
        canvas.style.position = 'fixed';
        canvas.style.width = innerWidth + 'px';
        canvas.style.height = innerHeight*0.8 + 'px';
        canvas.style.top = innerHeight*0.2 + 'px';
    });
    

    【讨论】:

    • 它通过添加“加载”而不是“调整大小”来工作,因为我希望它出现在应用程序的开头以及调整大小时。非常感谢
    • 我认为将 Canvas 大小设置为 Div 并将 Div 设置为我想要的 0.8 会更好,因为这样内容 Div 的高度为 0。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 2012-08-23
    • 1970-01-01
    相关资源
    最近更新 更多