开发者

HTML/Jquery question about Canvas resizing - $(window).resize vs $(window).load/$(document).ready

开发者 https://www.devze.com 2023-03-21 07:40 出处:网络
I\'m currently working on an app that\'ll run using HTML5\'s canvas element. I have code working to resize the Canvas to fit the size of the window as it resized as follows:

I'm currently working on an app that'll run using HTML5's canvas element. I have code working to resize the Canvas to fit the size of the window as it resized as follows:

<script type="text/javascript">
$(window).resize(function(){
var canvas = document.getElementById('canvas');
canvas.width=window.innerWidth;
canvas.height = window.innerHeight;
});
</script>

However, I want my canvas to be fully sized from the get-go, not just when开发者_Python百科 somebody resizes the screen. For some reason, when I copy the code above, except I change $(window).resize to $(window).load or $(document).ready, the canvas does not get set to the size of the window to begin with.

Does anybody see something wrong with what I'm trying to do that I'm not seeing, or have any other ideas on how to achieve this?

Best, and thanks in advance,

Sami

EDIT:

It would probably be good to note that I'm loading a ProcessingJS sketch into the canvas. I don't know whether the time that it takes for that to load ends up having an impact on things or not, but I figured I might as well make a mention of this...


The problem with resizing through .width/.height is that jQuery uses CSS for this. If you want to have more pixels for your canvas, use the width/height properties of the canvas instead. CSS will stretch it, HTML will increase the resolution.

$("#canvas")
    .attr('width', $(window).width())
    .attr('height', $(window).height());

http://jsfiddle.net/Jdjxa/1/


Try something like:

function resizeCanvas() {
    $("#canvas")
        .width($(window).width())
        .height($(window).height());
}

$(function() {
    // initial resize when the page has loaded
    resizeCanvas();

    // bind the resize event to the window
    $(window).resize(resizeCanvas);
});

Fiddle: http://jsfiddle.net/ANSrY/13/

0

精彩评论

暂无评论...
验证码 换一张
取 消