gpt4 book ai didi

fabricjs - 按扣织物。线成 45 度角

转载 作者:行者123 更新时间:2023-12-05 01:02:08 26 4
gpt4 key购买 nike

我正在尝试在fabricJS 中使用fabric.Line(),以便当用户开始绘制一条线时,它会捕捉到与起点成45 度角的八个角度之一。这类似于使用 Adob​​e 产品时按住 shift 键。用fabricJS可以吗?

最佳答案

2020 年 3 月编辑

  • 捕捉旋转现在是 fabric.js 中的内置功能

原答案:

您必须在鼠标移动期间检查您正在构建的角度并将其近似为 45° 度线。

var canvas = new fabric.Canvas('c', {
selection: false
});

var line, isDown, points;

canvas.on('mouse:down', function(o) {
isDown = true;
var pointer = canvas.getPointer(o.e);
points = [pointer.x, pointer.y, pointer.x, pointer.y];
line = new fabric.Line(points, {
strokeWidth: 2,
fill: 'red',
stroke: 'red',
originX: 'left',
originY: 'center'

});
canvas.add(line);
});

canvas.on('mouse:move', function(o) {
if (!isDown) return;
var pointer = canvas.getPointer(o.e);

var startX = points[0];
var startY = points[1];
var x2 = pointer.x - startX;
var y2 = pointer.y - startY;
var r = Math.sqrt(x2*x2 + y2*y2);
var angle = (Math.atan2(y2, x2) / Math.PI * 180);

angle = (angle) % 360 + 180;

if (angle <= 22.5 || angle >= 337.5) {
angle = 0;
} else if (angle <= 67.5) {
angle = 45;
} else if (angle <= 112.5) {
angle = 90;
} else if (angle <= 157.5) {
angle = 135
} else if (angle <= 202.5) {
angle = 180
} else if (angle <= 247.5) {
angle = 225
} else if (angle <= 292.5) {
angle = 270
} else if (angle < 337.5) {
angle = 315
}
angle -= 180;

var cosx = r * Math.cos(angle * Math.PI / 180);
var sinx = r * Math.sin(angle * Math.PI / 180);

line.set({
x2: cosx + startX,
y2: sinx + startY
});
canvas.renderAll();
});

canvas.on('mouse:up', function(o) {
isDown = false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>

<canvas id="c" width="500" height="500"></canvas>

关于fabricjs - 按扣织物。线成 45 度角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36275262/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com