gpt4 book ai didi

javascript - 在 Fabric.js Canvas 上添加网格

转载 作者:技术小花猫 更新时间:2023-10-29 12:19:36 25 4
gpt4 key购买 nike

我刚开始使用 Fabric.js(不得不说,我印象深刻)。

我想在织物对象上添加一个网格。在下面的代码中,我将我的网格 Canvas 放在 Fabric Canvas 上。这里的问题是,我现在无法移动我的织物对象!

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">

<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<script type='text/javascript' src='http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.2.0/fabric.all.min.js'></script>

</head>
<body>

<div style="height:480px;width:640px;border:1px solid #ccc;position:relative;font:16px/26px Georgia, Garamond, Serif;overflow:auto;">

<canvas id="rubber" width="800" height="800"
style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="myCanvas" width="800" height="800"
style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>

<script>
//<![CDATA[
$(window).load(function(){
$(document).ready(function () {

function renderGrid(x_size,y_size, color)
{
var canvas = $("#myCanvas").get(0);
var context = canvas.getContext("2d");

context.save();
context.lineWidth = 0.5;
context.strokeStyle = color;

// horizontal grid lines
for(var i = 0; i <= canvas.height; i = i + x_size)
{
context.beginPath();
context.moveTo(0, i);
context.lineTo(canvas.width, i);
context.closePath();
context.stroke();
}

// vertical grid lines
for(var j = 0; j <= canvas.width; j = j + y_size)
{
context.beginPath();
context.moveTo(j, 0);
context.lineTo(j, canvas.height);
context.closePath();
context.stroke();
}

context.restore();
}

renderGrid(10,15, "gray");
});

});//]]>

var canvas = new fabric.Canvas('rubber');
canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }));

canvas.selectionColor = 'rgba(0,255,0,0.3)';
canvas.selectionBorderColor = 'red';
canvas.selectionLineWidth = 5;
</script>


</body>
</html>

我希望 Fabric 本身有一种方法可以做到这一点。

任何帮助都会很棒,谢谢!

最佳答案

这两行代码可以工作:

var gridsize = 5;
for(var x=1;x<(canvas.width/gridsize);x++)
{
canvas.add(new fabric.Line([100*x, 0, 100*x, 600],{ stroke: "#000000", strokeWidth: 1, selectable:false, strokeDashArray: [5, 5]}));
canvas.add(new fabric.Line([0, 100*x, 600, 100*x],{ stroke: "#000000", strokeWidth: 1, selectable:false, strokeDashArray: [5, 5]}));
}

关于javascript - 在 Fabric.js Canvas 上添加网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17255867/

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