Background
I saw a question in the Q & A today:Use the lineto method of canvas to draw the diagonal line, but is the picture incorrect?
This is a very common misunderstanding. I 'd like to explain it to you here.
Principle
On W3:
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.
The intrinsic dimensions ofCanvas
Element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. however, the element can be sized arbitrarily by a style sheet. during rendering, the image is scaled to fit this layout size.
Actually, what I have already said is quite clear.Defining width and height in a canvas is different from defining width and height in a style,The width and height of the canvas label are the actual width and height of the canvas. The width and height of the style are the height and width of the canvas rendered in the browser. If the width and height of the canvas are not specified or the value is incorrect, it is set to the default value (width: 300px, height: 150px ).
We can use the width and height of the style to scale the canvas. See the following example.
Example
ExampleCodeAs follows:
<! Doctype html >
< Html >
< Head >
< Title > Demo </ Title >
< Meta HTTP-equiv = "Content-Type" Content = "Text/html; charsets = UTF-8" />
< Script Type = "Text/JavaScript" >
Function Drawdiagonal (ID ){
VaR Canvas = Document. getelementbyid (ID );
VaR Context = Canvas. getcontext ( " 2d " );
Context. beginpath ();
Context. moveTo ( 0 , 0 );
Context. lineto ( 100 , 100 );
Context. Stroke ();
}
Window. onload = Function (){
Drawdiagonal ( " Diagonal1 " );
Drawdiagonal ( " Diagonal " );
Drawdiagonal ( " Diagon_3 " );
}
</ Script >
</ Head >
< Body >
< Canvas ID = "Diagonal1" Style = "Border: 1px solid ;" Width = "100px" Height = "100px" > </ Canvas >
< Canvas ID = "Diagonal" Style = "Border: 1px solid; width: 200px; Height: 200px ;" Width = "100px" Height = "100px" > </ Canvas >
< Canvas ID = "Diagon_3" Style = "Border: 1px solid; width: 200px; Height: 200px ;" > </ Canvas >
</ Body >
</ Html >