0

EDIT: I figured it out. in one of the attached script was window.onload what caused for canvas to be created after everything alse was already executed. So when I added a script the canvas yet did not exist :)

I cannot change the size of canvas element. I build typical website with Bootstrap and the code in my index.html is like this:

<div id="container">
//some code
<div id="divForCanvas">
</div>

</div>

<script src="js/index2.js"></script>

in the index2.js I append canvas as a child of

<div id="divForCanvas"></div>

What happens is that the generated canvas has different width and height than its div parent.

Is there a way to adjust size of canvas after it was already generated (without editing index2.js) ?

user3784950
  • 65
  • 10
  • Possible duplicate of [Canvas width and height in HTML5](http://stackoverflow.com/questions/4938346/canvas-width-and-height-in-html5) – rmalviya Mar 21 '17 at 03:51

1 Answers1

0

A canvas element has a size in pixels, which applies to the bitmap you draw onto, and it has a CSS size like any other HTML element. These two are not the same (exactly like how a JPEG has a size in pixels but can be displayed at any size on screen), but you can set either one at any time.

The CSS size can be set in the normal ways, via a stylesheet, the style property of the <canvas> element, or through the JS myCanvas.style.* properties.

The size of the canvas contents can be set through the width and height properties of the <canvas> tag, or the JS myCanvas.width and myCanvas.height properties. Note that these are numbers, not CSS values, so you would say "<canvas width='200'>", not "<canvas width='200px'>". Setting either value will immediately clear the canvas contents, and in fact is the easiest way to do so.

Like an <img>, a <canvas> element is displayed by default at its 'natural' size, i.e. its size in pixels, unless its CSS width and height are set to depend on the containing element (for example if you set width:100%).

bobtato
  • 1,157
  • 1
  • 9
  • 11
  • thx for answer, I realised the problem is more because I have no idea how I can select the canvas element. I see element canvas when I inspect the page but document.getElementsByTagName('canvas') returns empty array! Do you know why is that ? – user3784950 Mar 21 '17 at 06:13
  • That shouldn't happen. How about document.getElementById('divForCanvas').firstChild or similar? – bobtato Mar 21 '17 at 08:51
  • I figured it out, in index2.js was window.onload what basically was creating canvas element in the end, so when I was adding normal script in my index.html the canvas element was not yet created! thx for help mate – user3784950 Mar 22 '17 at 05:03