fabric库 对齐的8种实现 && 辅助线的实现

本文档介绍了在canvas库fabric.js中如何添加辅助线以及实现8种不同的对象对齐方式。作者分享了开发过程中的代码示例,并提到在短时间内应用高中数学知识完成任务。虽然可能存在bug,作者欢迎读者提供修改建议。
摘要由CSDN通过智能技术生成

前言


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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值