【发布时间】:2020-12-05 19:05:05
【问题描述】:
我为代码道歉,它处于我正在积极使用的状态。
在 Konva JS 中,我正在创建标签。这基本上是一个组,它有一个形状和文本元素。形状是从数据库中动态绘制的,每个 db 行都有坐标、形状(正方形、圆形等)、大小和旋转。这些乘以取决于屏幕尺寸的比例。我有一个工作解决方案,我已经使用了几个星期,但我也有一个改变形状形状的功能。所以我按下一个按钮,它会更新数据库(例如将正方形更改为圆形),然后重绘画布。因为从正方形到圆形从从左上角绘制的形状变为从中心绘制的形状,所以它会弄乱坐标。我决定改用宽度/2 偏移量绘制矩形,这样矩形也可以从中心绘制。
我随后不断地打破它,我现在根本无法使文本居中。 无论形状、大小或旋转如何,我都需要居中文本。
当前代码
//Gets table array from SQL
tables = callPhpFunction('getTablesInRoom', room);
tables = JSON.parse(tables);
numberOfTables = tables.length;
index = 0;
tableLayer = new Konva.Layer();
tableLayer.add(transformer);
//For every table
while(index < numberOfTables){
tableNumber = tables[index]['tablenumber'];
offset_x = 0;
offset_y = 0;
pos_x = parseInt(tables[index]['posx']) * scale;
pos_y = parseInt(tables[index]['posy']) * scale;
shape = tables[index]['shape'];
tableWidth = parseInt(tables[index]['width']) * scale;
tableHeight = parseInt(tables[index]['height']) * scale;
rotation = parseInt(tables[index]['rotation']);
fillColor = "gray";
strokeColor = "black";
var table = new Konva.Label({
x: pos_x,
y: pos_y,
draggable:canDrag
});
pos_x = 0;
pos_y = 0 ;
//If the shape is a square, rectangle, or undefined
if(shape != "circle" && shape != "ellipse" && shape != "longellipse"){
offset_x = tableWidth/2
offset_y = tableHeight/2
table.add(new Konva.Rect({
width: tableWidth,
height: tableHeight,
offsetX: offset_y,
offsetY: offset_y,
height: tableHeight,
fill: fillColor,
stroke: strokeColor,
strokeWidth: 4
}));
//If shape is a circle or ellipse
} else {
table.add(new Konva.Ellipse({
radiusX: tableWidth/2,
radiusY: tableHeight/2,
fill: fillColor,
stroke: strokeColor,
strokeWidth: 4
}));
//Can't remember why this is here, but it seems to work/ Think if these are reused when the text is drawn it centers them.
pos_x = -tableWidth/2;
pos_y = -tableHeight/2;
}
//Gets the first shape (ellipse or rectangle) in the label. I think is equivalent to getTag()
innerShape = getInnerShape(table);
//Rotates the inner shape, while leaving text unRotated.
if(rotation != 0){
canvasX = pos_x + (tableWidth/2)
canvasY = pos_y + (tableHeight/2)
rotateAroundPoint(innerShape, rotation, {x:canvasX, y:canvasY });
}
//Currently approach is to get center based on the client rectangle. It's not working
box = table.getClientRect();
box_x = box.x + box.width / 2;
box_y = box.y + box.height / 2;
table.add(new Konva.Text({
width: tableWidth,
height: tableHeight,
x: box_x,
y: box_y,
text: tableNumber,
verticalAlign: 'middle',
align: 'center',
fontSize: 24,
fontFamily: 'Calibri',
fill: 'black',
listening: false
}))
【问题讨论】:
-
如果形状旋转,文本是否意味着旋转?
-
没有。因此,为什么我要对形状应用旋转,而不是对文本应用旋转。这让我很生气,因为我无法将文本的位置与形状很好地联系起来。我将尝试使用纯 HTML div 或 SVG
标签: javascript canvas konvajs