有什么辦法可以畫一個內接圓的正方形,正方形的角與圓的圓周相切并且半徑為R?它應該看起來像附加的影像。當然,矩形應該是正方形。
這是我到目前為止所擁有的:
function draw() {
const canvas = document.getElementById('circle');
if (canvas.getContext) {
const ctx = canvas.getContext('2d');
const X = canvas.width / 2;
const Y = canvas.height / 2;
const R = 50;
const angle = 45 * (Math.PI / 180);
const G = Math.sin(angle) * R;
ctx.beginPath();
ctx.arc(X, Y, R, 0, 2 * Math.PI, false);
ctx.lineWidth = 2;
ctx.strokeStyle = '#0000FF';
ctx.stroke();
}
}
canvas {
position: absolute;
height: 250px;
width: 250px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<body onload="draw()">
<div style="text-align:center;" , style="position: absolute">
<canvas id="circle" width="150" height="150"></canvas>
</div>
</body>

uj5u.com熱心網友回復:
請將其添加到您的繪圖功能中:
const cos45 = 0.7071;
// squareSide = cos45 * R * 2;
const halfOfSquareSide = cos45 * R;
ctx.beginPath();
ctx.rect(X - halfOfSquareSide, Y - halfOfSquareSide, halfOfSquareSide * 2 , halfOfSquareSide * 2);
ctx.lineWidth = 2;
ctx.strokeStyle = '#FF0000';
ctx.stroke();
uj5u.com熱心網友回復:
一種方法是首先使圓適合畫布尺寸,然后相應地計算,以獲得圓和正方形的變數。畫布是一個正方形,所以我不明白為什么我們需要兩個不同的高度和寬度變數。canvas.width = canvas.height所以我們可以用canvas.width它來做所有的計算。

function draw() {
const canvas = document.getElementById('circle');
if (canvas.getContext) {
const ctx = canvas.getContext('2d');
// Circle
const r = canvas.width/2,
angle = 45*(Math.PI/180),
g = Math.sin(angle)*r;
drawCircle(canvas.width, r);
function drawCircle(diameter, radius){
ctx.beginPath();
ctx.arc(diameter/2, diameter/2, radius, 0, 2 * Math.PI, false);
ctx.lineWidth = 2;
ctx.strokeStyle = '#0000FF';
ctx.stroke();
}
// Square
const squareWidth = Math.sqrt(2*r**2),
startX = (canvas.width - squareWidth) / 2,
startY = startX;
drawSquare(startX, startY, squareWidth);
function drawSquare(x, startY, width){
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(startX width, startY);
ctx.lineTo(startX width, startY width);
ctx.lineTo(startX, startY width);
ctx.lineTo(startX, startY);
ctx.stroke();
}
}
}
canvas {
position: absolute;
height: 150px;
width: 150px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<body onload="draw()">
<div style="text-align:center;" , style="position: absolute">
<canvas id="circle" width="150" height="150"></canvas>
</div>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/394568.html
標籤:javascript html html5-canvas
上一篇:如何使用jquery忽略所有空格來計算真正的文本總數?
下一篇:簡單的if陳述句es6
