我试图填充一个矩形,在30度的对角线,不会被画布剪裁。每一行都应该在画布的边缘开始和结束,但不要离开画布。
我得到了一些结果,但我很难理解如何才能解决这些问题,使线条分布均匀:
到目前为止,我得到的代码如下:
const myCanvas = document.getElementById("myCanvas");
const _ctx = myCanvas.getContext("2d");
const canvasWidth = 600;
const canvasHeight = 300;
// Helper function
const degToRad = (deg) => deg * (Math.PI / 180);
const angleInDeg = 30;
const spaceBetweenLines = 16;
const lineThickness = 16;
_ctx.fillStyle = `black`;
_ctx.fillRect(0, 0, canvasWidth, canvasHeight);
const step = (spaceBetweenLines + lineThickness) / Math.cos(angleInDeg * (Math.PI / 180));
for (let distance = -canvasHeight + step; distance < canvasWidth; distance += step) {
let x = 0;
let y = 0;
if(distance < 0) {
// Handle height
y = canvasHeight - (distance + canvasHeight);
} else {
// Handle height
x = distance;
}
const lineLength = canvasHeight - y;
const slant = lineLength / Math.tan(degToRad((180 - 90 - angleInDeg)));
const x2 = Math.min(x + slant, canvasWidth);
const y2 = y + lineLength;
_ctx.beginPath();
_ctx.moveTo(x, y);
_ctx.lineTo(x2, y2);
_ctx.lineWidth = lineThickness;
_ctx.strokeStyle = 'green';
_ctx.stroke();
}
我想要实现的是画一个图案,在那里我可以控制线的角度,而线不是被画布剪裁的。参考照片(线条末端没有平面):
有什么帮助吗?
我的例子出现在Javascript中,但更多的是我试图把我的头脑集中起来的逻辑。因此,我愿意接受其他语言中的建议/例子。
更新1,如果线的角度是45度,你会看到沟槽变得正确的左侧。所以我怀疑在我的步态计算中我需要做一些不同的事情。
我的当前代码基于这个答案。
发布于 2020-11-05 16:36:51
也许试着用这样的方法来画线
for(var i = 0; i < 20; i++){
_ctx.fillrect(i * spaceBetweenLines + lineThickness, -100, canvas.height + 100, lineThickness)
}
https://stackoverflow.com/questions/64706836
复制