javascript - 在圆圈周围绘制形状

标签 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;
}

但是,这些正方形并不均匀,我在制作它们时遇到了麻烦。我该如何实现这一目标?

最佳答案

使用三 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/

相关文章:

canvas - 从 FB Canvas 调用 getLoginStatus 不会触发

javascript - HTML5 Canvas 覆盖在网页之上?

iOS View Controller 在旋转后移动

javascript - 使用 Splice Javascript 在数组中增量添加元素

javascript - console.log 和进度事件 - 仅在 100% 时显示

javascript - 如何在jsp中使用javascript动态创建下拉框?

javascript - 了解 HTML 5 Canvas 缩放和平移顺序

ios - SKAction 改变 anchor ?

three.js - 围绕给定轴和角度的枢轴点正确旋转对象

javascript - 如何从 UIWebView 获取数据传递到 Objective-c IOS 中的 native 应用程序