How to set font-size dynamically in JointJs? - javascript

I am developing a JointJs Application,I need to set font-size for a text inside a rectangle.
$('#FText,#FTextHeight,#FTextWidth,#FTextSize').on('keyup change', function () {
var FtHeight = $('#FTextHeight').val();
var FtWidth = $('#FTextWidth').val();
var FtSize = parseInt($('#FTextSize').val());
var txt = $('#FText').val();
graph2.clear();
if (txt.length > 0) {
$('#FTexterror').empty();
var myFtext = new joint.shapes.basic.Rect({
position: { x: 50, y: 50 },
size: { width: FtWidth, height: FtHeight },
attrs: {
rect: {
fill: 'white', stroke: outerColor, 'class': 'customtext',
},
text: {
text: txt, 'letter-spacing': 1, 'font-size': FtSize,
fill: outerColor, 'font-size': 11, 'y-alignment': 'middle',
}
}
});
graph2.addCells([myFtext]);
}
else {
$('#FTexterror').empty().append('*Enter valid text');
}
});
the above code is not working while setting font-size for the text.
Kindly help me on this

try this
$('.input-text')
.val(rect.attr('text/font-size')) //set initial value
.on('keyup', function () {
var val = $(this).val();
rect.attr('text/font-size', val);
});
complete demo: https://jsfiddle.net/vtalas/sav49mj4/

Related

How do you apply Smart Routing on links with ports on JointJS?

I am trying to apply smart routing of links with the use of ports using JointJS. This documentation shows the one I am trying to achieve. The example on the docs though shows only the programmatic way of adding Link from point A to point B. How do you do this with the use of ports?
Here's my code: JSFiddle.
HTML:
<html>
<body>
<button id="btnAdd">Add Table</button>
<div id="dbLookupCanvas"></div>
</body>
</html>
JS
$(document).ready(function() {
$('#btnAdd').on('click', function() {
AddTable();
});
InitializeCanvas();
// Adding of two sample tables on first load
AddTable(50, 50);
AddTable(250, 50);
});
var graph;
var paper
var selectedElement;
var namespace;
function InitializeCanvas() {
let canvasContainer = $('#dbLookupCanvas').parent();
namespace = joint.shapes;
graph = new joint.dia.Graph({}, {
cellNamespace: namespace
});
paper = new joint.dia.Paper({
el: document.getElementById('dbLookupCanvas'),
model: graph,
width: canvasContainer.width(),
height: 500,
gridSize: 10,
drawGrid: true,
cellViewNamespace: namespace,
validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
return (magnetS !== magnetT);
},
snapLinks: {
radius: 20
}
});
//Dragging navigation on canvas
var dragStartPosition;
paper.on('blank:pointerdown',
function(event, x, y) {
dragStartPosition = {
x: x,
y: y
};
}
);
paper.on('cell:pointerup blank:pointerup', function(cellView, x, y) {
dragStartPosition = null;
});
$("#dbLookupCanvas")
.mousemove(function(event) {
if (dragStartPosition)
paper.translate(
event.offsetX - dragStartPosition.x,
event.offsetY - dragStartPosition.y);
});
// Remove links not connected to anything
paper.model.on('batch:stop', function() {
var links = paper.model.getLinks();
_.each(links, function(link) {
var source = link.get('source');
var target = link.get('target');
if (source.id === undefined || target.id === undefined) {
link.remove();
}
});
});
paper.on('cell:pointerdown', function(elementView) {
resetAll(this);
let isElement = elementView.model.isElement();
if (isElement) {
var currentElement = elementView.model;
currentElement.attr('body/stroke', 'orange');
selectedElement = elementView.model;
} else
selectedElement = null;
});
paper.on('blank:pointerdown', function(elementView) {
resetAll(this);
});
$('#dbLookupCanvas')
.attr('tabindex', 0)
.on('mouseover', function() {
this.focus();
})
.on('keydown', function(e) {
if (e.keyCode == 46)
if (selectedElement) selectedElement.remove();
});
}
function AddTable(xCoord = undefined, yCoord = undefined) {
// This is a sample database data here
let data = [
{columnName: "radomData1"},
{columnName: "radomData2"}
];
if (xCoord == undefined && yCoord == undefined)
{
xCoord = 50;
yCoord = 50;
}
const rect = new joint.shapes.standard.Rectangle({
position: {
x: xCoord,
y: yCoord
},
size: {
width: 150,
height: 200
},
ports: {
groups: {
'a': {},
'b': {}
}
}
});
$.each(data, (i, v) => {
const port = {
group: 'a',
args: {}, // Extra arguments for the port layout function, see `layout.Port` section
label: {
position: {
name: 'right',
args: {
y: 6
} // Extra arguments for the label layout function, see `layout.PortLabel` section
},
markup: [{
tagName: 'text',
selector: 'label'
}]
},
attrs: {
body: {
magnet: true,
width: 16,
height: 16,
x: -8,
y: -4,
stroke: 'red',
fill: 'gray'
},
label: {
text: v.columnName,
fill: 'black'
}
},
markup: [{
tagName: 'rect',
selector: 'body'
}]
};
rect.addPort(port);
});
rect.resize(150, data.length * 40);
graph.addCell(rect);
}
function resetAll(paper) {
paper.drawBackground({
color: 'white'
});
var elements = paper.model.getElements();
for (var i = 0, ii = elements.length; i < ii; i++) {
var currentElement = elements[i];
currentElement.attr('body/stroke', 'black');
}
var links = paper.model.getLinks();
for (var j = 0, jj = links.length; j < jj; j++) {
var currentLink = links[j];
currentLink.attr('line/stroke', 'black');
currentLink.label(0, {
attrs: {
body: {
stroke: 'black'
}
}
});
}
}
Any help would be appreciated. Thanks!
The default link created when you draw a link from a port is joint.dia.Link.
To change this you can use the defaultLink paper option, and configure the router you would like.
defaultLink documentation reference
const paper = new joint.dia.Paper({
el: document.getElementById('dbLookupCanvas'),
model: graph,
width: canvasContainer.width(),
height: 500,
gridSize: 10,
drawGrid: true,
cellViewNamespace: namespace,
validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
return (magnetS !== magnetT);
},
snapLinks: {
radius: 20
},
defaultLink: () => new joint.shapes.standard.Link({
router: { name: 'manhattan' },
connector: { name: 'rounded' },
})
});
You could also provide several default options in the paper.
defaultLink: () => new joint.shapes.standard.Link(),
defaultRouter: { name: 'manhattan' },
defaultConnector: { name: 'rounded' }

Changing xaxis label from echarts library

var data = [];
var dataCount = 10;
var startTime = +new Date();
var categories = ['categoryA', 'categoryB', 'categoryC'];
var types = [
{name: 'JS Heap', color: '#7b9ce1'},
{name: 'Documents', color: '#bd6d6c'},
{name: 'Nodes', color: '#75d874'},
{name: 'Listeners', color: '#e0bc78'},
{name: 'GPU Memory', color: '#dc77dc'},
{name: 'GPU', color: '#72b362'}
];
// Generate mock data
echarts.util.each(categories, function (category, index) {
var baseTime = startTime;
for (var i = 0; i < dataCount; i++) {
var typeItem = types[Math.round(Math.random() * (types.length - 1))];
var duration = Math.round(Math.random() * 10000);
data.push({
name: typeItem.name,
value: [
index,
baseTime,
baseTime += duration,
duration
],
itemStyle: {
normal: {
color: typeItem.color
}
}
});
baseTime += Math.round(Math.random() * 2000);
}
});
function renderItem(params, api) {
var categoryIndex = api.value(0);
var start = api.coord([api.value(1), categoryIndex]);
var end = api.coord([api.value(2), categoryIndex]);
var height = api.size([0, 1])[1] * 0.6;
var rectShape = echarts.graphic.clipRectByRect({
x: start[0],
y: start[1] - height / 2,
width: end[0] - start[0],
height: height
}, {
x: params.coordSys.x,
y: params.coordSys.y,
width: params.coordSys.width,
height: params.coordSys.height
});
return rectShape && {
type: 'rect',
shape: rectShape,
style: api.style()
};
}
option = {
tooltip: {
formatter: function (params) {
return params.marker + params.name + ': ' + params.value[3] + ' ms';
}
},
title: {
text: 'Profile',
left: 'center'
},
dataZoom: [{
type: 'slider',
filterMode: 'weakFilter',
showDataShadow: false,
top: 400,
height: 10,
borderColor: 'transparent',
backgroundColor: '#e2e2e2',
handleIcon: 'M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z', // jshint ignore:line
handleSize: 20,
handleStyle: {
shadowBlur: 6,
shadowOffsetX: 1,
shadowOffsetY: 2,
shadowColor: '#aaa'
},
labelFormatter: ''
}, {
type: 'inside',
filterMode: 'weakFilter'
}],
grid: {
height:300
},
xAxis: {
min: startTime,
scale: true,
axisLabel: {
formatter: function (val) {
return Math.max(0, val - startTime) + ' ms';
}
}
},
yAxis: {
data: categories
},
series: [{
type: 'custom',
renderItem: renderItem,
itemStyle: {
normal: {
opacity: 0.8
}
},
encode: {
x: [1, 2],
y: 0
},
data: data
}]
};
Hi, everyone!! I am working on the echarts library, the only thing i want to change data is the axisLabel from Xaxis part.
What i mean is, for example, "2019-11-5, 2019-11-6...."and so on. So, i hope someone can help me out, thank you so much!!!
Hi, everyone!! I am working on the echarts library, the only thing i want to change data is the axisLabel from Xaxis part.
What i mean is, for example, "2019-11-5, 2019-11-6...."and so on. So, i hope someone can help me out, thank you so much!!!
First, create an array of dates like
var dates = ['2019-11-5','2019-10-3','2019-2-2','2019-1-4','2019-12-5'];
then in xAxis -> axisLabel return date
axisLabel: {
formatter: function (val,index) {
return dates[index];
}
}

HighCharts onClick get column data on Stacked Column Chart

I have a stacked Column chart which gives my a list of columns. Each column has a name.
What I need to is is to get the name of the column that has been clicked on.
I have a couple of alerts in the series section which is where I want to data to be called from.
Here is the code:
var chart;
$(function () {
$.ajax({
url: 'url here',
method: 'GET',
async: false,
success: function(result) {
themainData = result;
}
});
var mainData = [themainData];
var chlist=[];
var votList=[];
var comList=[];
for (var i = 0; i < mainData[0].cha.length; i++) {
var obj = mainData[0].cha[i];
var chlst = obj.name;
var vl = obj.sta.vot;
var cl = obj.sta.com;
chlist.push(chlst);
votList.push(vl);
comList.push(cl);
}
//var chlist = ['Ch 1', 'Ch 2', 'Ch 3', 'Ch 4'];
////var votList = [10, 9, 8, 7];
//var comList = [10, 9, 8, 7];
var chart = {
type: 'column',
};
var title = {
text: 'vot and com'
};
var xAxis = {
categories: chlist
};
var yAxis ={
min: 0,
title: {
text: 'cha'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
};
var legend = {
align: 'right',
x: -30,
verticalAlign: 'top',
y: 25,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
borderColor: '#CCC',
borderWidth: 1,
shadow: false
};
var tooltip = {
formatter: function () {
return '<b>' + this.x + '</b><br/>' +
this.series.name + ': ' + this.y + '<br/>' +
'Total: ' + this.point.stackTotal;
}
};
var plotOptions = {
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textShadow: '0 0 3px black'
}
}
}
};
var credits = {
enabled: false
};
var series= [{
name: 'vot',
data: votList,
events: {
click: function (event) {
alert('vot Here');
alert ('show: '+ this.cha +', value: '+ this.y);
}
}
}, {
name: 'com',
data: comList,
events: {
click: function (event) {
alert('com Here');
alert ('show: '+ this.cha +', value: '+ this.y);
}
}
}];
var json = {};
json.chart = chart;
json.title = title;
json.xAxis = xAxis;
json.yAxis = yAxis;
json.legend = legend;
json.tooltip = tooltip;
json.plotOptions = plotOptions;
json.credits = credits;
json.series = series;
$('#container').highcharts(json);
//end
});
How can I do this?
You can add column.point.click event callback function and inside this function alert points name using alert(this.name)
plotOptions: {
column: {
stacking: 'normal',
keys: ['x', 'y', 'name'],
point: {
events: {
click: function() {
alert(this.name)
}
}
}
}
},
Here you can find an example how it can work:
http://jsfiddle.net/grz4zaLc/1/

Total of values in HighCharts Pie Chart

Is there a way to get a grand total of values in legend or any other place in pie charts?
Here is the code with legend ,but instead of adding the total of percentage,i want to display the total of values..
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie',
width: 500,
borderWidth: 2
},
title: {
text: 'demo'
},
credits: {
enabled: false
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
y: 30,
labelFormat: '{name} ({percentage:.1f}%)',
navigation: {
activeColor: '#3E576F',
animation: true,
arrowSize: 12,
inactiveColor: '#CCC',
style: {
fontWeight: 'bold',
color: '#333',
fontSize: '12px'
}
}
},
tooltip: {
formatter: function() {
return Highcharts.numberFormat(this.percentage, 2) + '%<br />' + '<b>' + this.point.name + '</b><br />Rs.: ' + Highcharts.numberFormat(this.y, 2);
}
},
series: [{
data: (function () {
var names = 'Ari,Bjartur,Bogi,Bragi,Dánjal,Dávur,Eli,Emil,Fróði,Hákun,Hanus,Hjalti,Ísakur,' +
'Johan,Jóhan,Julian,Kristian,Leon,Levi,Magnus,Martin,Mattias,Mikkjal,Nóa,Óli,Pauli,Petur,Rói,Sveinur,Teitur',
arr = [];
Highcharts.each(names.split(','), function (name) {
arr.push({
name: name,
y: Math.round(Math.random() * 100)
});
});
return arr;
}()),
showInLegend: true
}]
});
});
I would use the Renderer.text to annotate the chart (and not do it in the legend since you have so many data points).
chart: {
events: {
load: function(event) {
var total = 0; // get total of data
for (var i = 0, len = this.series[0].yData.length; i < len; i++) {
total += this.series[0].yData[i];
}
var text = this.renderer.text(
'Total: ' + total,
this.plotLeft,
this.plotTop - 20
).attr({
zIndex: 5
}).add() // write it to the upper left hand corner
}
}
},
Fiddle example.
In addition to Mark's answer, to calculate the total, we do not need the for-loop statement. So, the code can be reduced.
chart: {
events: {
load: function(event) {
var total = this.series[0].data[0].total;
var text = this.renderer.text(
'Total: ' + total,
this.plotLeft,
this.plotTop - 20
).attr({
zIndex: 5
}).add() // write it to the upper left hand corner
}
}
},

Titanium mobile Javascript objects

Ok so I'm new to Titanium and I'm pretty much a noob at Javascript
I tried doing this:
app.view.newMatrix = function() {
return {
matrix = Titanium.UI.createWindow({
title:'Add a New Matrix',
backgroundColor:'stripped',
navBarHidden: false
}),
// navbar buttons
cancel = Titanium.UI.createButton({
title:'Cancel'
}),
save = Titanium.UI.createButton({
title:'Save',
style:Titanium.UI.iPhone.SystemButton.SAVE
}),
name_label = Titanium.UI.createLabel({
text: "Matrix Name:",
font: { fontsize: 12, fontstyle: 'italic', color: '#336699' },
height: 35,
top: 35,
left: 30,
width: 150,
color: "black"
}),
name = Titanium.UI.createTextArea({
color: '#336699',
height: this.name_label.height,
top: this.name_label.top + 35,
left: this.name_label.left - 10,
width: 275,
borderRadius:15
}),
setItems = function() {
this.win.add(this.name);
this.win.add(this.name_label);
this.win.add(this.desc);
this.win.add(this.desc_label);
Ti.API.info("label:"+ this.name_label.height);
return this.win.open({modal: true, animation: true});
}
}
}
then called it like this:
app.controller.home = function() {
var home = app.view.home();
home.setItems();
home.butn.addEventListener("click", function(e){
app.controller.newMatrix();
});
home.butn2.addEventListener("click", function (e) {
matrix_table(tab);
});
home.butn3.addEventListener("click", function(e){
newItem();
});
home.butn5.addEventListener("click", function (e) {
item_table();
});
}
I did this because I saw a Titanium MVC suggestion here but I don't get why it returns an anonymous object. I can't access properties like name_label from within the name object.
I figured out that I should do this instead:
app.view.newMatrix = function() {
this.matrix = Titanium.UI.createWindow({
title:'Add a New Matrix',
backgroundColor:'stripped',
navBarHidden: false
}),
// navbar buttons
this.cancel = Titanium.UI.createButton({
title:'Cancel'
}),
this.save = Titanium.UI.createButton({
title:'Save',
style:Titanium.UI.iPhone.SystemButton.SAVE
}),
this.name_label = Titanium.UI.createLabel({
text: "Matrix Name:",
font: { fontsize: 12, fontstyle: 'italic', color: '#336699' },
height: 35,
top: 35,
left: 30,
width: 150,
color: "black"
}),
this.name = Titanium.UI.createTextArea({
color: '#336699',
height: this.name_label.height,
top: this.name_label.top + 35,
left: this.name_label.left - 10,
width: 275,
borderRadius:15
}),
this.setItems = function() {
this.win.add(this.name);
this.win.add(this.name_label);
this.win.add(this.desc);
this.win.add(this.desc_label);
Ti.API.info("label:"+ this.name_label.height);
return this.win.open({modal: true, animation: true});
}
}
and call it like this:
app.controller.home = function() {
return {
getView: function() {
var home = app.view.home();
home.setItems();
home.butn.addEventListener("click", function(e){
app.controller.newMatrix();
});
home.butn2.addEventListener("click", function (e) {
matrix_table(tab);
});
home.butn3.addEventListener("click", function(e){
newItem();
});
home.butn5.addEventListener("click", function (e) {
item_table();
});
}
}
}
But I don't know why the first example doesn't work. I mean aren't properties the same as variables? Also I do know that the second example is an object too.. is that how I'm supposed to do them? Also with the second example is the new keyword optional? Should I use it? I kinda wanted to stay away from that cause I'm not sure when I should use it.
thanks I hope I made sense. I do have it working but I don't know if the second example is the right way to go....

Categories

Resources