views:

48

answers:

2

Hi all, I have to set the attributes 'width' and 'height' for a canvas element, depending on the available screen resolution. Setting them statically from html works (ex. <canvas id="canv" width="1600" ... ). From Javascript I can't do it. I've googled and searched in SO but I didn't find anything that works. I am using JQuery and I've tried unsuccessfully the following (the same for height attribute)

$('#canv').setAttribute('width',screen.availWidth);
$('#canv').attr('width',screen.availWidth);
$('#canv').data('width',screen.availWidth);
$('#canv').width = screen.availWidth;
$('#canv').css('width',screen.availWidth);

I did the same putting var cv = $('#canv')[0].getContext("2d"); and changing $('#canv') with cv but with no result.

bb

+1  A: 

You can do it like this, but I'm not sure if the screen size is what you're after:

$('#canv').width(screen.availWidth);​

You can see a demo here

Nick Craver
This one half solved it, thanks; as you can see in the http://jsfiddle.net/pUcjV/2/ demo, now the area has wanted dimensions.. but I can't draw canvas pixel per pixel.. it just draws the background in the standard dimensions and then maximizes it..
Francesco
Moreover consider I'm using canvas with HTML 5.. just thinking.. maybe it requires attributes on the main source..
Francesco
+1  A: 

I changed the code on jsfiddle.net/pUcjV/2 to

$('#canv').attr("width", screen.availWidth);    
$('#canv').attr("height", screen.availHeight);  
circlesBG (cv, col, screen.availWidth, screen.availHeight);

from

circlesBG (cv, col, screen.availWidth, screen.availHeight);
$('#canv').width(screen.availWidth);    
$('#canv').height(screen.availHeight);    

This produced stars over the whole canvas. Is this the desired result? I'm using Chrome 5.0.375.99.

Castrohenge
It works :) now I see if it works in the original page too, but I think this solves everything :) thanks so much .. I will try to rate these answers even if I've less than 15 of reputation :D
Francesco
It works definitely.. Weird thing: if you compare the canvas made with the attributes in html http://jsfiddle.net/pUcjV/7/ to the last canvas we made with the attributes inserted by js http://jsfiddle.net/pUcjV/8/ the first one has antialiasing, the last one hasn't :\
Francesco
Got the anti-aliasing working. Just retrieved the context after the size change - http://jsfiddle.net/pUcjV/11/. This was again with Chrome 5.0.375.99.
Castrohenge
thanks.. I just got it working by inserting the script directly in the html http://jsfiddle.net/7eCxx/1 but yours is a cleaner solution :) thanks for the help
Francesco