我对 Canvas 比较陌生,我想知道如何旋转(和绘制)正方形。现在,我从 5 个正方形开始,希望它们距中心 150 米。就目前情况而言,我有这个:
let context = document.getElementById("drawingSurface");
ctx = context.getContext('2d');
let numberOfSquares = 5;
let radius = 150;
let angles = 360 / numberOfSquares;
let toRadians = angles * Math.PI/180;
for(let i = 0; i<= numberOfSquares;i++){
ctx.save();
ctx.translate(200,200);
ctx.rotate(toRadians);
ctx.fillRect(0,radius,20,20);
ctx.restore();
toRadians += toRadians;
}
但是,这些正方形并不均匀,我在制作它们时遇到了麻烦。我该如何实现这一目标?
最佳答案
使用三 Angular 函数找到一定 Angular 点。
不要使用变换矩阵来获取框位置,而是使用三 Angular 函数 sin 和 cos。
获取某个 Angular 位置(ang 以弧度为单位)
var x = Math.cos(ang) * distance;
var y = Math.sin(ang) * distance;
获取与点 px,py 成一定 Angular 位置
var x = Math.cos(ang) * distance + px;
var y = Math.sin(ang) * distance + py;
下面的代码示例
var canvas = document.createElement("canvas");
canvas.width = innerWidth - 40;
canvas.height = innerHeight - 40;
var ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
function drawCircle(x,y,radius,fillC,strokeC,lineW){
ctx.fillStyle = fillC;
ctx.strokeStyle = strokeC;
ctx.lineWidth = isNaN(lineW) ? ctx.lineWidth : lineW;
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
if(fillC !== null && fillC !== undefined){
ctx.fill();
}
if(strokeC !== null && strokeC !== undefined){
ctx.stroke();
}
}
function drawSquare(x,y,size,fillC,strokeC,lineW){
ctx.fillStyle = fillC;
ctx.strokeStyle = strokeC;
ctx.lineWidth = isNaN(lineW) ? ctx.lineWidth : lineW;
ctx.beginPath();
ctx.rect(x - size / 2, y - size / 2, size, size);
if(fillC !== null && fillC !== undefined){
ctx.fill();
}
if(strokeC !== null && strokeC !== undefined){
ctx.stroke();
}
}
const startAngle = Math.PI * -0.5;
const boxSize = Math.min(canvas.width,canvas.height) / 8;
const circleX = canvas.width / 2;
const circleY = canvas.height / 2;
const radius = Math.min(canvas.height,canvas.width) /2 - boxSize /2 - 4;
const colors = ["red", "blue", "blue", "blue", "blue", "blue", "blue", "blue"];
const boxCount = colors.length;
ctx.lineJoin = "round";
drawCircle(circleX,circleY,radius,"black");
for(var i = 0; i < boxCount; i++){
var ang = i * ((Math.PI * 2) / boxCount) + startAngle;
var x = Math.cos(ang) * radius + circleX;
var y = Math.sin(ang) * radius + circleY;
drawSquare(x, y, boxSize, colors[i], "white", 3);
}
关于javascript - 在圆圈周围绘制形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40581093/