1

I am new to javascript. And I can't understand why the codes not working the same. this is the canvas :

var canvas = document.getElementById("gameScreen");

var context = canvas.getContext("2d")

context.fillRect(20, 20, 20, 20);
#gameScreen {
  background-color:coral;
  width:200px;
  height:200px;
  }
<!--<canvas id = "gameScreen" width= "200" height= "200" style="background-color:coral"></canvas> -->

<canvas id = "gameScreen"></canvas>

this is another canvas :

var canvas = document.getElementById("gameScreen");

var context = canvas.getContext("2d");

context.fillRect(20, 20, 20, 20);
#gameScreen {
  background-color:coral;
  }
<canvas id="gameScreen" width="200px" height="200px"></canvas>

why the first one is not working as the second one??

1 Answers1

0

The default canvas size is 300x150, when dimensions set via style (CSS) it only stretches it to that size.

The first thing to know is that a canvas element has intrinsic dimensions = number of pixels in the inside coordinate space (set by the width and height attributes and properties). It also has extrinsic dimensions (style.width and style.height) which is the number of pixels that the image takes within the webpage. The intrinsic pixels are scaled to fit the extrinsic space.

Source: @yonran

Here is an example, click on canvas:

var canvas = document.getElementById("gameScreen");

var context = canvas.getContext("2d")

context.fillRect(20, 20, 20, 20);
#gameScreen {
  background-color:coral;
  transition: width 1s ease-in-out;
  width: 400px;
  height: 200px;
}
#gameScreen.small
{
  width: 200px;
  height: 200px;
}
<!--<canvas id = "gameScreen" width= "200" height= "200" style="background-color:coral"></canvas> -->

<canvas id = "gameScreen" onclick="this.classList.toggle('small')"></canvas>
vanowm
  • 9,466
  • 2
  • 21
  • 37