简体   繁体   English

将画布放大到父级的宽度和高度

[英]enlarging canvas to parent width and height

I am trying to draw some shapes on the HTML5 canvas using Javascript. 我正在尝试使用Javascript在HTML5画布上绘制一些形状。

When the width and height of the canvas is of a hard coded size like for example 800x600 everything works fine. 当画布的宽度和高度为硬编码尺寸(例如800x600)时,一切正常。

What I would like to do is to stretch the width of the canvas to fit the parent (the size of the parent can be anything). 我想做的是拉伸画布的宽度以适合父对象(父对象的大小可以是任何东西)。 When I apply the width: 100% and height: 100% properties in the CSS, the shapes drawn start from a different starting point from what it actually should. 当我在CSS中应用width:100%和height:100%属性时,绘制的形状从与实际位置不同的起点开始。

A sample of what I am working on is provided in this link: http://jsfiddle.net/jR4ne/ 此链接提供了我正在处理的示例: http : //jsfiddle.net/jR4ne/

Please help me out in understanding what is going wrong here. 请帮助我了解这里出了什么问题。 It appears that the canvas is being stretched instead of being enlarged. 似乎画布是在拉伸而不是在放大。 I want the canvas to be enlarged to fit the parent. 我希望将画布放大以适合父级。

For your case, you shouldn't use CSS to change the size. 对于您的情况,不应使用CSS来更改大小。 You have to specify the width and height in pixel for Canvas. 您必须为Canvas指定宽度和高度(以像素为单位)。 You can add the code below to your JS () and it will meet your requirement: 您可以将以下代码添加到JS()中,它将满足您的要求:

canvasNode.width = document.body.scrollWidth;
canvasNode.height = document.body.scrollHeight;

Of course, your parent may refer to different things, you need to change the width and height accordingly. 当然,您的父母可能会提到不同的事物,您需要相应地更改宽度和高度。 Please refer to here for more info: http://www.howtocreate.co.uk/tutorials/javascript/browserwindow 请参阅此处以获取更多信息: http : //www.howtocreate.co.uk/tutorials/javascript/browserwindow

It looks like the canvas is being initialised too early, before it has been resized to width 100%: the drawn rectangles also render in stretched mode. 在将画布调整为宽度100%之前,似乎初始化画布还为时过早:绘制的矩形也以拉伸模式渲染。 I would suggest putting the initialisation code into an onload function eg 我建议将初始化代码放入onload函数中,例如

<body onload="setupCanvas()">

or with jQuery: 或使用jQuery:

$( function() { setupCanvas(); } );

I would also suggest removing the width/height attributes from the HTML (not sure if they are just there temporarily as the css width 100% is not working?) 我还建议从HTML中删除width / height属性(不确定CSS宽度100%无法正常工作,它们是否只是暂时存在?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM