Canvas needs to define the width and height directly in the label. canvas label Definition
This article mainly introduces why canvas needs to define the width and height directly in the label. This is a special test, which is very practical and recommended to friends.
In the past, when I used canvas to draw images, I wrote width and height directly in the canvas label. There is no problem, but I have not explored why width and height should be directly written in the canvas label, this is because the examples of various materials are written in this way. Today, Wang sir raised a question: If you write the width and height in <style>, let's see what's different. I tried the following and there was a problem.
First look at the Code:
The Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8">
<Title> canvas </title>
<Meta name = "Keywords" content = "">
<Meta name = "author" content = "@ my_programmer">
<Style type = "text/css">
Body {margin: 0 ;}
Canvas {margin: 20px;
/* Width: 400px;
Height: 300px ;*/
}
</Style>
</Head>
<Body onload = "draw ()">
<Canvas id = "canvas" width = 400 height = 300 style = "border: 1px solid # f00;"> </canvas>
<Script>
Function draw (){
Var canvas = document. getElementById ('canvas ');
Var context = canvas. getContext ('2d ');
Context. beginPath ();
Context. moveTo (20, 20 );
Context. lineTo (200,100 );
Context. lineWidth = 5;
Context. stroke ();
}
</Script>
</Body>
</Html>
1. Width: 400; Height: 300; effects written directly in <canvas>:
2. Delete the width and height in <canvas>, width: 400; Height: 300; effects written in <style>:
Why are the effects different?
Like other labels, canvas can also define styles through css. However, it should be noted that the default width and height of the canvas are 300px * 150px, and the width and height of the canvas are defined in css. In fact, the canvas with the width and height of 300px * 150px is stretched, if you draw a canvas in this case, the image you get may be the deformation effect. Therefore, when drawing a canvas, you should directly define the width and height in the canvas label.