前言
- 这两天公司业务需要这个canvas库,但是中文文档很少,fabricjs官网
- 但是需求还是要写的,开始整吧
- 我找的,更多fabric中文文档内容
fabric 添加 辅助线 ?
效果 ?
代码 ?
/**
* @说明 给fabirc中的元素加入辅助线(网上资料,修改使用)
* @param {canvas} 参数说明:需要传入 new fabric.Canvas() 的那个对象
* @host https://my.oschina.net/xmqywx/blog/1941539
* @time 2019.6.12
*/
export const initAligningGuidelines = canvas => {
var ctx = canvas.getSelectionContext(), // getSelectionContext 获取选择上下文
aligningLineOffset = 5, // 对齐线条偏移
aligningLineMargin = 4, // 对齐线边距
aligningLineWidth = 1, // 对齐线条宽度
aligningLineColor = '#666666', // 颜色
viewportTransform, // 视图端口转换
zoom = 1;
// 画垂直线
function drawVerticalLine(coords) {
drawLine(
coords.x + 0.5,
coords.y1 > coords.y2 ? coords.y2 : coords.y1,
coords.x + 0.5,
coords.y2 > coords.y1 ? coords.y2 : coords.y1);
}
// 画水平线
function drawHorizontalLine(coords) {
drawLine(
coords.x1 > coords.x2 ? coords.x2 : coords.x1,
coords.y + 0.5,
coords.x2 > coords.x1 ? coords.x2 : coords.x1,
coords.y + 0.5);
}
// 画线
function drawLine(x1, y1, x2, y2) {
ctx.save();
ctx.lineWidth = aligningLineWidth;
ctx.strokeStyle = aligningLineColor;
ctx.beginPath();
ctx.moveTo(((x1+viewportTransform[4])*zoom), ((y1+viewportTransform[5])*zoom));
ctx.lineTo(((x2+viewportTransform[4])*zoom), ((y2+viewportTransform[5])*zoom));
ctx.stroke();
ctx.restore();
}
// 范围
function isInRange(value1, value2) {
value1 = Math.round(value1);
value2 = Math.round(value2);
for (var i = value1 - aligningLineMargin, len = value1 + aligningLineMargin; i <= len; i++) {
if (i === value2) {
return true;
}
}
return false;
}
var verticalLines = [],
horizontalLines = [];
// 移动
canvas.on('mouse:down', function () {
viewportTransform = canvas.viewportTransform;
zoom = canvas.getZoom();
});
// 对象移动事件(移动到某个点才具有辅助线的功能)
canvas.on('object:moving', function(e) {
var activeObject = e.target,
canvasObjects = canvas.getObjects(),
activeObjectCenter = activeObject.getCenterPoint(),
activeObjectLeft = activeObjectCenter.x,
activeObjectTop = activeObjectCenter.y,
activeObjectBoundingRect = activeObject.getBoundingRect(),
activeObjectHeight = activeObjectBoundingRect.height / viewportTransform[3],
activeObjectWidth = activeObjectBoundingRect.width / viewportTransform[0],
horizontalInTheRange = false,
verticalInTheRange = false,
transform = canvas._currentTransform;
if (!transform) return;
// It should be trivial to DRY this up by encapsulating (repeating) creation of x1, x2, y1, and y2 into functions,
// but we're not doing it here for perf. reasons -- as this a function that's invoked on every mo