do.
do.

Reputation: 617

The difference between "100" and "100px" in html

i was about to create a html5 canvas the size of 500px*500px:

<canvas id="stone" width="500px" height="500px"></canvas>

and stroke a line from (70px, 70px) to (140px, 140px) on it:

var canvas = document.getElementById( "stone" );
var context;

try {
    context = canvas.getContext( "2d" );
} catch( e ) {
    $( "support" ).html( "HTML5 canvas is not supported by your browser." );
}

context.beginPath();
context.moveTo( 70, 70 );
context.lineTo( 140, 140 );
context.stroke();

but i was given a square with the line that wasn't start at (70px, 70px) obviously: enter image description here

i thought there was somethings wrong with the size of my canvas, so i removed the suffix "px" from width and height property of canvas and kept others unchanged:

<canvas id="stone" width="500" height="500"></canvas>

and i got a rectangle with a right positioned line this time: enter image description here

what's the difference between "500" and "500px"? how can i make this canvas a right size?

Upvotes: 7

Views: 2271

Answers (1)

Joey
Joey

Reputation: 354694

See the spec:

The canvas element has two attributes to control the size of the coordinate space: width and height. These attributes, when specified, must have values that are valid non-negative integers. The rules for parsing non-negative integers must be used to obtain their numeric values. If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead. The width attribute defaults to 300, and the height attribute defaults to 150.

Lengths in HTML are always unit-less. Length units are part of CSS and thus don't appear in HTML (except for style).

Upvotes: 4

Related Questions