最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Fail on setting attribute for canvas from Javascript - Stack Overflow

programmeradmin5浏览0评论

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

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

Share Improve this question edited Jul 7, 2010 at 13:58 gc5 asked Jul 6, 2010 at 20:11 gc5gc5 9,89829 gold badges96 silver badges152 bronze badges 2
  • 1 Are you trying to maximize it to the browser viewable area, or to the user's screen size? – Nick Craver Commented Jul 6, 2010 at 20:38
  • I'm trying to maximize it to the browser viewable area.. – gc5 Commented Jul 7, 2010 at 16:56
Add a ment  | 

2 Answers 2

Reset to default 7

I changed the code on jsfiddle/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.

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

发布评论

评论列表(0)

  1. 暂无评论