Home >Web Front-end >H5 Tutorial >Detailed introduction to why the width and height of the HTML5 canvas are written in the
In the past, when I used canvas to draw pictures, I always wrote the width and height directly in the canvas tag. There was no problem, but I never explored why the width and height should be written directly in the canvas tag, because each data This is what is written in the examples. Today, Sir Wang raised a question: If the width and height are written in c9ccee2e6ea535a969eb3f532ad9fe89, let’s see what difference there will be. I tried the following myself, and sure enough there is a problem.
Let’s take a look at the code first:
<!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; The effect of writing directly in 5ba626b379994d53f7acf72a64f9b697:
2. Delete the width and height in 5ba626b379994d53f7acf72a64f9b697, width: 400; height: 300; the effect of writing in c9ccee2e6ea535a969eb3f532ad9fe89:
##Why Will the effects of the two be different? Canvas, like other tags, can also be styled through CSS. But what needs to be noted here is that the default width and height of canvas is 300px * 150px. Defining the width and height for the canvas in css actually stretches the canvas with a width and height of 300px * 150px.If Under such circumstances, when you perform canvasdrawing, the graphics you get may be deformed. Therefore, when drawing on canvas, should directly define the width and height in the canvas tag.
The above is the detailed content of Detailed introduction to why the width and height of the HTML5 canvas are written in the