在圆圈中绘制形状

时间:2016-11-14 02:28:09

标签: javascript canvas rotation

我对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;
}

然而,方块并不统一,我无法制作它们。我怎么能达到这个目的?

1 个答案:

答案 0 :(得分:1)

使用trig函数查找角度点。

不是使用变换矩阵来获得框位置,而是使用trig函数sin和cos。

以一定角度获得位置(ang以弧度表示)

var x = Math.cos(ang) * distance;
var y = Math.sin(ang) * distance;

从点px,py

获得一个角度的位置
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 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 boxCount = 8;
ctx.lineJoin = "round";


drawCircle(circleX,circleY,radius,"black");
for(var i = 0; i < boxCount; i++){
    var ang = i * ((Math.PI * 2) / boxCount);
    var x = Math.cos(ang) * radius + circleX;
    var y = Math.sin(ang) * radius + circleY;
    drawSquare(x,y,boxSize,"red","white",3);
}