Canvas is stretched when using CSS but normal with width / height properties
It seems that the width
and height
attributes determine the width or height of the canvas’s coordinate system, whereas the CSS properties just determine the size of the box in which it will be shown.
This is explained in the HTML specification:
The
canvas
element has two attributes to control the size of the element’s bitmap:width
andheight
. 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. Thewidth
attribute defaults to 300, and theheight
attribute defaults to 150.
Why do I need to have the width at 400px and height at 200px in a canvas element for this?
The style=
defines the scaling - use width=
and height=
to set the size of the box.
Also explained here (MDN canvas element).
The displayed size of the canvas can be changed using CSS, but if you do this the image is scaled during rendering to fit the styled size, which can make the final graphics rendering end up being distorted.
It is better to specify your canvas dimensions by setting the width and height attributes directly on the elements, either directly in the HTML or by using JavaScript.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var a = document.getElementById("3d");
var b = a.getContext("2d");
b.beginPath();
b.moveTo(0,50);
b.lineTo(0,100);
b.lineTo(50,150);
b.lineTo(50,100);
b.lineTo(0,50);
b.lineTo(50,0);
b.lineTo(100,50);
b.lineTo(100,100);
b.lineTo(50,150);
b.lineTo(50,100);
b.lineTo(100,50);
b.stroke();
});
</script>
</head>
<body>
<canvas id="3d" width="200" height="200" style="border:1px solid black"></canvas>
</body>
</html>
Related Topics
Why It Is Not Taking 100% Height in Material Design
Does Height and Width Not Apply to Span
Fill Remaining Vertical Space With CSS Using Display:Flex
Using Only Css, Show Div on Hover Over Another Element
Text in a Flex Container Doesn't Wrap in Ie11
Css to Select/Style First Word
Remove Ie10'S "Clear Field" X Button on Certain Inputs
How to Break a List into Columns
How to Set Opacity in Parent Div and Not Affect in Child Div
Play Multiple CSS Animations At the Same Time
Cannot Change Font Size of Text Field in Material Ui
Is Float For Layout Bad? What Should Be Used in Its Place
Align Child Elements of Different Blocks
Why Aren't My Grid-Template-Areas With Ascii Art Not Working
How to Show Only Corner Borders
Difference Between Normalize.Css and Reset Css
How Does the CSS Block Formatting Context Work
Rotated Elements in CSS That Affect Their Parent'S Height Correctly