Problems encountered: html/11467.html">The reason why the canvas element is deformed and distorted
There are three sizes for a DOM element: style size, html size, and css size.
When using the canvas element, the default width and height of the canvas element is 300px * 150px. The default size here is html size.
To better help understanding, take painting as an example. The artboard is css size or style size, and the canvas is html size.
If we do not display the html size of the specified canvas element, but specify its css size in the css file. The result is very confusing.
For example, we draw a circle with a radius of 50px on a default canvas of 300px * 150px.
<html lang=zh><head> <meta charset=UTF-8> <title>canvas size</title> <style> #canvas { width: 200px; height: 200px; } </style></head>< body><div> <canvas id=canvas></canvas></div><script> window.onload = function () { const canvas = document.getElementById(canvas); const ctx = canvas.getContext(2d); ctx.beginPath(); ctx.strokeStyle = #aaaaaa; ctx.arc(100, 100, 50, 0, 2 * Math.PI); ctx.stroke(); ctx. closePath(); };</script></body></html>
The final results displayed are as follows:
It can be seen that the size of the canvas is indeed 200 * 200. But the circle has turned into an ellipse, and the shape has deformed. Why is this?
What happens if the size set by css is removed?
It can be seen that the graph is normal at this time. The size of the canvas is indeed the default 300*150.
From comparison and imagination we can draw the following conclusions:
Initially we drew a circle on the canvas of 300150. After the drawing is completed, we want to change the size of the canvas to 200200. At the same time, the canvas is still the same canvas and will not be changed.
What works is to stretch the canvas. Assuming that the canvas has elasticity, then a canvas stretches from 300150 to 200200. The major semi-axis of the circle on the canvas becomes 1.33 times the original size, and the minor semi-axis becomes 0.68 times. At this point the circle is naturally an ellipse.
in conclusion:When using canvas to draw, in order to avoid unnecessary trouble, you must remember to set the width and height of the HTML size for the canvas element.
SummarizeThe above is a brief analysis of the impact of the html size and css size of the canvas element on the visual element introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. . I would also like to thank everyone for your support of the VeVb martial arts website!
If you think this article is helpful to you, you are welcome to reprint it, please indicate the source, thank you!