动态设置画布尺寸时,文档高度在调整大小时变大 [英] Document height grows on resize when setting canvas dimensions dynamically

查看:218
本文介绍了动态设置画布尺寸时,文档高度在调整大小时变大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要获得一个canvas元素来占据整个文档的高度和窗口宽度,所以当我调整窗口大小时,canvas元素伸展起来,实际上,给我一个全屏幕画布。然而,实际发生的是,无论窗口如何调整大小,文档高度(因此,画布高度)都会增加。

I'm trying to get a canvas element to take up the entirety of the document height and window width, so that when I resize the window, the canvas element stretches with it, in effect, giving me a full screen canvas. What is actually happening, though, is the document height(and consequently, the canvas height) increases no matter how the window is resized.

我正在使用此代码:

$(document).ready(function () {
    $("#wrapper").before("<div id='background'><canvas id='depth' width='"+$(window).width()+"'height='"+$(document).height()+"'></canvas></div>");
    $(window).resize(function() {
        $("#depth").attr("width",$(window).width());
        $("#depth").attr("height",$(document).height());
    });
});

我也尝试使用DOM脚本具有完全相同的结果。这是一个调整画布元素的怪癖,还是我错过了一些东西?

I've also tried using DOM scripting with the exact same result. Is this a quirk of resizing canvas elements, or am I missing something?

这是问题在行动

推荐答案

我认为这应该工作吗?它改编自我写的代码,以确保 #wrapper 总是拉伸到屏幕的底部,如果内容没有这样做(但我删除了最小高度约束)。我相信你也可以根据你对宽度的需要。

I think this should work? It's adapted from code I wrote to ensure #wrapper always stretched to reach the bottom of the screen if the content didn't already make it do so (but I removed the minimum height constraints). I'm sure you can adapt this to your needs for width as well.

你错误的总结是在数学计算什么高度应该

The summary of where you were going wrong is in the maths to calculate what the height should be in the event of the window being negatively resized.

我还留下了几个额外的位,你可以看到处理一些浏览器不一致时计算窗口高度;解决了一些我发现的错误。

I've also left in a couple of extra bits that you can see which deal with some browser inconsistencies when calculating window height; solved a couple of bugs I found.

$(document).ready(function() {resize()});
$(window).resize(function() {resize()});

// Calculate Required Wrapper Height
function resize() {
    // I think this is for Opera's benefit?
    var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();

    // IE7
    if (jQuery.browser.msie) {
        if(parseInt(jQuery.browser.version) == 7) {
            viewportHeight -= 3;
        }
    }

    if($('#wrapper').height() > viewportHeight) {
        $('.content').height($('#wrapper').height() - viewportHeight);
    }

    if($('#wrapper').height() < viewportHeight) {
        $('.content').height(viewportHeight - $('#wrapper').height());
    }
}

这篇关于动态设置画布尺寸时,文档高度在调整大小时变大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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