[英]Aspect Ratio, Height / Width in HTML-Canvas
I have a square in which I want to draw a simple point, The square width & height defined in percentage. 我有一个正方形,想在其中绘制一个简单的点,即以百分比定义的正方形宽度和高度。 the problem is that the point comes out wrong (oval shaped). 问题在于该点出了错(椭圆形)。
I've created the following jsfiddle which reflects my issue: 我创建了以下jsfiddle来反映我的问题:
https://jsfiddle.net/uhycv0pj/ https://jsfiddle.net/uhycv0pj/
<div style="width: 200px; height:200px; border:1px solid #d3d3d3;">
<canvas id="myCanvas" style="width: 100%; height:100%; border:1px solid #d3d3d3;"></canvas>
</div>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(50, 50, 10, 0, 2 * Math.PI);
ctx.fill();
</script>
You have to define the size of the Canvas in Pixels first: 您必须首先以像素为单位定义画布的大小:
var c = document.getElementById("myCanvas");
c.width = 200
c.height = 200
You can also do it by "100%" with: 您还可以通过“ 100%”完成此操作:
var c = document.getElementById("myCanvas");
c.width = c.parentElement.clientWidth
c.height = c.parentElement.clientHeight
But remember, this wont change if your parent-element's width/height change. 但是请记住,如果父元素的宽度/高度发生变化,则不会改变。 You will have to do it again - and setting a canvas' width/height will delete it's content, so you will have to draw it again. 您将不得不再次执行-设置画布的宽度/高度将删除其内容,因此您将不得不再次绘制它。
DEMO: DEMO:
var c = document.getElementById("myCanvas"); c.width = c.parentElement.clientWidth c.height = c.parentElement.clientHeight var ctx = c.getContext("2d"); ctx.beginPath(); ctx.arc(50, 50, 10, 0, 2 * Math.PI); ctx.fill();
<div style="width: 200px; height:200px; border:1px solid #d3d3d3;"> <canvas id="myCanvas" style="width: 200px; height:200px; border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag.</canvas> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.