从cordinates fabric js画一条路径

时间:2016-05-24 10:41:23

标签: javascript canvas html5-canvas fabricjs

我正在开发一个需要在IOS和Android中复制的画布应用程序。因此,目标是使用Web创建的任何内容都必须在其他平台中复制,反之亦然。

在网络中我使用Fabric JS作为我的画布库,我使用JSON方法构建来保存和重新创建画布,而IOS开发人员正在使用基于点的系统来保存x,y协调画布中绘制的所有对象和线条。 IOS开发人员正在使用宽度和x坐标来展示画布的高度,以使对象和线在所有设备中保持平衡。

我能够将基于Web的画布转换为所需的基于点的系统。但现在的挑战是将基于点的系统转换为基于结构的Web画布。处理对象很容易处理,但我需要一些帮助,以便我如何从数据库中的逗号分隔值重新创建路径。

以下是使用IOS应用程序保存在数据库中的路径示例。

[
  "{0.88156813, 0.67090207}",
  "{0.86200052, 0.67090207}",
  "{0.83264917, 0.67908657}",
  "{0.81308156, 0.67908657}",
  "{0.77883828, 0.68727112}",
  "{0.75437874, 0.68727112}",
  "{0.72013545, 0.68727112}",
  "{0.69567597, 0.68727112}",
  "{0.67121649, 0.69545561}",
  "{0.65164888, 0.69545561}",
  "{0.63208127, 0.70364016}",
  "{0.61251366, 0.70364016}",
  "{0.59294611, 0.72000921}",
  "{0.58316231, 0.7281937}",
  "{0.58316231, 0.73637825}"
]

如何从给定数据重新创建路径,其中第一个值是x cordinate,第二个值是y cordinate。

这方面的任何指导都会非常有帮助。

此致

1 个答案:

答案 0 :(得分:1)

像这样的东西,我把画布的宽度和高度当作最大值= 1,这样对x,y是宽度或高度的百分比。

如果您在区间[-1,1]中与负值坐标,请使用:

points.push({
       x : (width\2 * coordinates[i].x),
       y : (height\2 * coordinates[i].y)
       }); 

并在线条图中添加偏移量:

canvas.add(new fabric.Line([x1, y1, x2, y2], {
        left: width\2,
        top: height\2,
        stroke: 'red'
    }));

当考虑可能的路径值在[0,1]之间时的响应:



var coordinates = [
  {x : 0.2, y: 0.2},
  {x : 0.88156813, y: 0.67090207},
  {x: 0.86200052, y: 0.67090207},
  {x: 0.83264917, y: 0.67908657},
  {x: 0.81308156,  y: 0.67908657},
  {x: 0.77883828,  y: 0.68727112},
  {x: 0.75437874,  y: 0.68727112},
  {x: 0.72013545,  y: 0.68727112},
  {x: 0.69567597,  y: 0.68727112},
  {x: 0.67121649,  y: 0.69545561},
  {x: 0.65164888,  y: 0.69545561},
  {x: 0.63208127,  y: 0.70364016},
  {x: 0.61251366,  y: 0.70364016},
  {x: 0.59294611,  y: 0.72000921},
  {x: 0.58316231,  y: 0.7281937},
  {x: 0.58316231,  y: 0.73637825}
];

var canvas = new fabric.Canvas('c');
var width = canvas.width;//0.00 to 1.00
var height = canvas.height;//0.00 to 1.00

var points = [];

//define your points from 0 to width and from 0 to height
for(i =0; i < coordinates.length; i++)
{
   points.push({
   x : (width * coordinates[i].x),
   y : (height * coordinates[i].y)
   });
}

//drow lines
for(i =0; i < points.length - 1; i++)
{

//alert(points[i].x);
    canvas.add(new fabric.Line([points[i].x, points[i].y, points[i+1].x, points[i+1].y], {
          stroke: 'blue'
       }));
}

canvas.add(new fabric.Text('x=0.00', { left: 20, top: 5, fontSize: 10 }));
canvas.add(new fabric.Text('y=1.00', { left: 360, top: 5, fontSize: 10 }));
canvas.add(new fabric.Text('y=0.00', { left: 5, top: 20, fontSize: 10 }));
canvas.add(new fabric.Text('y=1.00', { left: 5, top: 380, fontSize: 10 }));
&#13;
canvas {
    border-width: 1px;
    border-style: solid;
    border-color: #000;
}
&#13;
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<canvas id="c" width="400" height="400"></canvas>
&#13;
&#13;
&#13;