Home > Software design >  Setting the width/height inside HTML differs from what happens in CSS
Setting the width/height inside HTML differs from what happens in CSS

Time:02-18

I am having a lot of confusion trying to figure out what is happening. I am drawing some boxes in using javaScript. I am following this guide to recreate breakout.

Breakout Tutorial

The trouble that I am having is that the canvas size does not work if I am using external css to set the width heigth like so below, the css doesnt work.

#myCanvas{
width: "480";
height: "320";
}

However if I change the code to in my html to this

    <canvas id = "myCanvas" width ="480" height="320">    
</canvas>

The box is the right size. Why cant I set the height and width out of the html?

Here is a JSfiddle of the box with the right size.

If you move the css width/height over to the external side it doesn't work anymore. What gives?

CodePudding user response:

There is a difference between inline tags (id, class, width, height, style, ...) and css attributes (width, height, font-size, ...).

If you want to use the css attributes width and height you need the remove the "" and add the unit.

e.g.

#myCanvas{
  width: 480px;
  height: 320px;
}

You can also add css inline using the style attribute:

<canvas id = "myCanvas" style = "width: 480px; height: 320px">   

CodePudding user response:

A canvas has 2 sizes, the dimension of the pixels in the canvas (it's backingstore or drawingBuffer) and the display size.

The number of pixels is set using the the canvas attributes in HTML.

<canvas id = "myCanvas" style = "width: 480px; height: 320px"> 

which is separate from width and height that are in canvas's CSS style.

myCanvas{ width: 480px;  height: 320px; 

Changed your code to understand better.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.rect(10, 10, 30, 20);
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.closePath();

ctx.beginPath();
ctx.arc(30, 80, 20, 0, Math.PI*2, false);
ctx.fillStyle = "green";
ctx.fill();
ctx.closePath();

ctx.beginPath();
ctx.rect(10, 140, 30, 40);
ctx.strokeStyle = "rgba(0, 0, 255, 0.5)";
ctx.stroke();
ctx.closePath();
canvas { 
         background:#eee; border:1px solid #ccc; 
         width:200px; 
         height:300px 
}
<canvas id="myCanvas" width="100" height="200"></canvas>

  • Related