Saving a canvas object as an image - Black background - javascript

This is a slightly frustrating problem. I am using a third party library called Javascript InfoVis Toolkit to generate a canvas image chart.
So the chart is built and is inserted into a canvas. The background of that image is white (like styled in css), but when I convert the image (I've tried different libraries and opening a new window all together) it is black.
<script type="text/javascript">
function saveImage(div_id) {
var canvas = document.getElementById("chart2-canvas");
Canvas2Image.saveAsJPEG(canvas);
}
</script>
<script type="text/javascript">
function init(jsonString, num){
var json = jsonString
var inj = 'chart' + num
var st = new $jit.ST({
injectInto: inj,
offsetX:25,
offsetY:900,
transition: $jit.Trans.Quart.easeInOut,
orientation: 'top',
Node: {
height:100,
width:100,
type: 'rectangle',
color: '#EEE',
overridable: true
},
Edge: {
type: 'line',
color: '#512',
overridable: true
},
Label: {
type: 'Native',
color: '#000000'
},
Tips: {
enable: false,
onShow: function(tip, node, isLeaf, domElement){
var html = "<p><b>" + node.name + "</b></p><br/>";
var data = node.data
if(data.image) {
html += "<img src=\""+ data.image +"\" width=50 height=65 class=\"album\" />";
}
if(data.email) {
html += "<p>"+data.email+"</p>";
}
if(data.title) {
html += "<p>"+data.title+"</p>";
}
if(data.phone) {
html += "<p>"+data.phone+"</p>";
}
tip.innerHTML = html;
}
}/*,
onCreateLabel:function(label,node) {
alert(node.name);
alert(node.data);
var html = "<b>" + node.name + "</b>";
var data = node.data;
if(data.title) {
html += "<br/><br/><i>" + data.title + "</i>";
}
label.id = node.id + "_" + num;
label.innerHTML = html;
var style = label.style;
style.width = 100 + 'px';
style.height = 100 + 'px';
style.cursor = 'pointer';
style.fontSize = '0.8em';
style.textAlign = 'center';
style.color='#321';
}*/
});
st.loadJSON(json);
st.compute();
st.onClick(st.root);
}
</script>
Save Image
<g:each in="${allJSON}" status="h" var="jsonInstance">
<div id="chart${h+1}">
<script type="text/javascript">
init(${jsonInstance}, ${h+1});
</script>
</div>
</g:each>
To recap:
I generate the charts in the code, all of which have a white background (which is right)
I save the image of the chart 2 (as a test), but the image that is saved is BLACK - apparently ignoring the canvas background.
Thanks for all help!

Are you sure the canvas doesn't have a transparent background? JPEGs don't support transparent backgrounds.
If it does have a transparent background, try drawing a white background on it first, then save it as a JPEG.

Related

Add picture issue when exporting Highcharts to pdf - Highcharts warning: Invalid tagName

I have an export of Highcharts into a pdf file with added text and images (based on this). It used to work until recently but now it's not exporting the added pictures, everything else is fine.
The JavaScript is throwing the following error "Highcharts warning: Invalid tagName image in config". Fiddle reproducing the error here.
The line that causes the problem is svgImg.appendChild(svgimg).
I'm not sure if I changed something or if there was a library change somewhere. Any help is appreciated.
Here is the js:
$(function () {
Highcharts.getSVG = function(charts,texts, options, callback) {
var svgArr = [],
top = 0,
width = 0,
newLine = false,
txt1;
addSVG = function(svgres,i) {
// Grab width/height from exported chart
var svgWidth = +svgres.match(
/^<svg[^>]*width\s*=\s*\"?(\d+)\"?[^>]*>/
)[1],
svgHeight = +svgres.match(
/^<svg[^>]*height\s*=\s*\"?(\d+)\"?[^>]*>/
)[1],
// Offset the position of this chart in the final SVG
svg;
if (svgWidth > 1100) {
if(i==5){
top = 1000;
svg = svgres.replace('<svg', '<g transform="translate(0,' + top + ')"');
}else{
svg = svgres.replace('<svg', '<g transform="translate(' + width + ', 0 )"');
}
top = Math.max(top, svgHeight);
} else {
if (newLine) {
if(i==4){
width = 1000;
}
svg = svgres.replace('<svg', '<g transform="translate(' + width + ', ' + top + ')"');
top += svgHeight;
width += svgWidth;
newLine = false;
} else {
newLine = true;
if(i==5){
top = 1000;
svg = svgres.replace('<svg', '<g transform="translate(0,' + top + ')" ');
}else{
svg = svgres.replace('<svg', '<g transform="translate(0,' + top + ')" ');
}
top = Math.max(top, svgHeight);
width += svgWidth;
//width = Math.max(width, chart.chartWidth);
}
}
svg = svg.replace('</svg>', '</g>');
svgArr.push(svg);
txt = texts[i];
txt1 = '<svg width="350" height="75" viewBox="0 0 350 75"><rect x="10" y="50"
width="300" height="40" style="fill: white; stroke:black;stroke-width:2"/><g
style="overflow:hidden; font-size:14; font-family: Arial"></text><text x="20" y="65"
style="fill: black">Text test text text</text></g><g style="overflow:hidden; font-
size:14; font-family: Arial"></text><text x="20" y="82" style="fill: black">Text
test text text</text></g></svg>' ;
svgArr.push(txt1);
},
exportChart = function(i) {
if (i === charts.length) {
// add SVG image to exported svg
addSVG(svgImg.outerHTML);
//console.log(top+'-----'+width);
return callback('<svg height="2000" width="2000" version="1.1"
xmlns="http://www.w3.org/2000/svg">' + svgArr.join('') + '</svg>');
}
charts[i].getSVGForLocalExport(options, {}, function() {
console.log("Failed to get SVG");
}, function(svg) {
addSVG(svg,i);
return exportChart(i + 1); // Export next only when this SVG is received
});
};
// console.log(svgArr);
exportChart(0);
};
Highcharts.exportCharts = function(charts,texts, options) {
options = Highcharts.merge(Highcharts.getOptions().exporting, options);
// Get SVG asynchronously and then download the resulting SVG
Highcharts.getSVG(charts,texts, options, function(svg) {
Highcharts.downloadSVGLocal(svg, options, function() {
console.log("Failed to export on client side");
});
});
};
//Set global default options for all charts
Highcharts.setOptions({
exporting: {
fallbackToExportServer: false // Ensure the export happens on the client side or not at all
}
});
var chart1 = new Highcharts.chart('container', {
chart: {
type: 'column',
styledMode: true
},
title: {
text: 'Styling axes and columns'
},
yAxis: [{
className: 'highcharts-color-0',
title: {
text: 'Primary axis'
}
}, {
className: 'highcharts-color-1',
opposite: true,
title: {
text: 'Secondary axis'
}
}],
plotOptions: {
column: {
borderRadius: 5
}
},
series: [{
data: [1, 3, 2, 4]
}, {
data: [324, 124, 547, 221],
yAxis: 1
}]
});
var texts = $('.HC');
function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
};
var svgImg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgImg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
svgImg.setAttribute('height', '200');
svgImg.setAttribute('width', '200');
svgImg.setAttribute('id', 'test');
var svgimg = document.createElementNS('http://www.w3.org/2000/svg', 'image');
svgimg.setAttribute('height', '768');
svgimg.setAttribute('width', '1024');
svgimg.setAttribute('id', 'testimg');
// convert image and add to svg image object
toDataURL('https://www.highcharts.com/samples/graphics/sun.png', function (dataUrl) {
svgimg.setAttributeNS('http://www.w3.org/1999/xlink', 'href', dataUrl);
});
svgimg.setAttribute('x', '0');
svgimg.setAttribute('y', '0');
svgImg.appendChild(svgimg);
$("#export2pdf").click(function() {
Highcharts.exportCharts([chart1],texts, {
type: 'application/pdf',
filename: 'Feedback',
});
});
});
It is related to the new Highcharts Security policy. You need to modify the default AST settings:
Highcharts.AST.allowedTags.push('image');
Highcharts.AST.allowedAttributes.push('xlink:href');
Live demo: https://jsfiddle.net/BlackLabel/8snjc6gy/
Docs: https://www.highcharts.com/docs/chart-concepts/security

Chart.js / Javascript How to Override Mouseout Event Listener

I am trying to use chart.js to create a bar chart with a custom html tooltip. I would like to include some interactive stuff in the tooltip. The problem is that by default, when the mouse leaves the chart canvas, the opacity of the tooltip goes to 0. I need to override the mouseout event so that users can interact with the tooltip.
The official documentation is good, but not comprehensive... I cannot find an official answer, so I have resorted to reviewing the open source code and my developer tools.
Using Google Chrome's developer tools, I can click on the canvas and look at the event listeners tab. Under mouseout, I see the following:
canvas#chart_0.dashboard-chart.chartjs-render-monitor chart.js 10969
removing this listener in the developer tools fixes the problem. when I click the link I can see the following code that is used to add the listener, and if I set a breakpoint I can see it being added:
...
addEventListener: function(chart, type, listener) {
var canvas = chart.canvas;
if (type === 'resize') {
// Note: the resize event is not supported on all browsers.
addResizeListener(canvas, listener, chart);
return;
}
var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
var proxies = expando.proxies || (expando.proxies = {});
var proxy = proxies[chart.id + '_' + type] = function(event) {
listener(fromNativeEvent(event, chart));
};
addEventListener(canvas, type, proxy);
},
...
Hover I get chart.js from a CDN and would prefer to override this with my own javascript, rather than rolling a customized version of chart.js. I can't figure out how to remove the handler, though. I have tried the following after the chart.js script loads:
$('canvas').off('mouseout');
$('canvas#chart_0').off('mouseout');
$('canvas#chart_0.dashboard-chart.chartjs-render-monitor').off('mouseout');
$('#chart_0').off('mouseout');
$('.chartjs-render-monitor').off('mouseout');
None of these selectors remove the event listener. I have also tried something to the effect of $('canvas#chart_0')[0].removeEventListener('mouseout') but this requires the listener as a parameter, and I'm not sure how to get a reference to that since it is passed anonymously. Can anyone recommend a way of getting rid of the default event listener, or a way to pass a configuration option to chart.js to override the default behavior? Thanks in advance.
For the following example I have used the sample provided on the custom tooltip documentation that are available here.
The object that is passed to the custom function, in this case tooltipModel, have a propriety that will be set to 0 when the cursor leaves the hovered item, if we ignore the line that hides the tooltip it will stay visible until you hovered another item.
So the lines that have to be changed are the following:
// Hide if no tooltip
if (tooltipModel.opacity === 0) {
tooltipEl.style.opacity = 0; // remove this line
return;
}
A full working example:
var ctx = document.getElementById('bar-chart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['A', ' B', ' C'],
datasets: [{
label: "Y",
data: [5, 2, 0]
},
{
label: "Z",
data: [7, 0, 3]
}
]
},
options: {
tooltips: {
enabled: false,
custom: function(tooltipModel) {
// Tooltip Element
var tooltipEl = document.getElementById('chartjs-tooltip');
// Create element on first render
if (!tooltipEl) {
tooltipEl = document.createElement('div');
tooltipEl.id = 'chartjs-tooltip';
tooltipEl.innerHTML = '<table></table>';
document.body.appendChild(tooltipEl);
}
// Hide if no tooltip
if (tooltipModel.opacity === 0) {
// remove the next line
//tooltipEl.style.opacity = 0;
return;
}
// Set caret Position
tooltipEl.classList.remove('above', 'below', 'no-transform');
if (tooltipModel.yAlign) {
tooltipEl.classList.add(tooltipModel.yAlign);
} else {
tooltipEl.classList.add('no-transform');
}
function getBody(bodyItem) {
return bodyItem.lines;
}
// Set Text
if (tooltipModel.body) {
var titleLines = tooltipModel.title || [];
var bodyLines = tooltipModel.body.map(getBody);
var innerHtml = '<thead>';
titleLines.forEach(function(title) {
innerHtml += '<tr><th>' + title + '</th></tr>';
});
innerHtml += '</thead><tbody>';
bodyLines.forEach(function(body, i) {
var colors = tooltipModel.labelColors[i];
var style = 'background:' + colors.backgroundColor;
style += '; border-color:' + colors.borderColor;
style += '; border-width: 2px';
var span = '<span style="' + style + '"></span>';
innerHtml += '<tr><td>' + span + body + '</td></tr>';
});
innerHtml += '</tbody>';
var tableRoot = tooltipEl.querySelector('table');
tableRoot.innerHTML = innerHtml;
}
// `this` will be the overall tooltip
var position = this._chart.canvas.getBoundingClientRect();
// Display, position, and set styles for font
tooltipEl.style.opacity = 1;
tooltipEl.style.position = 'absolute';
tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
tooltipEl.style.fontFamily = tooltipModel._bodyFontFamily;
tooltipEl.style.fontSize = tooltipModel.bodyFontSize + 'px';
tooltipEl.style.fontStyle = tooltipModel._bodyFontStyle;
tooltipEl.style.padding = tooltipModel.yPadding + 'px ' + tooltipModel.xPadding + 'px';
tooltipEl.style.pointerEvents = 'none';
}
}
}
});
#chartjs-tooltip {
opacity: 1;
position: absolute;
background: rgba(0, 0, 0, .7);
color: white;
border-radius: 3px;
-webkit-transition: all .1s ease;
transition: all .1s ease;
pointer-events: none;
-webkit-transform: translate(-50%, 0);
transform: translate(-50%, 0);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="bar-chart" width="400" height="200"></canvas>

Image gallery with href tag

I have a question
I have this code. The code used to display a gallery, and it works perfect. I want now that when you click on any picture I show it in bigger resolution. But when I put the href tag, the images not appear, if the link appears, but the images not appear.
<div class="container">
<div id="freewall" class="free-wall"></div>
<script type="text/javascript">
var temp = "<div class='brick' style='width:{width}px;'><img src='img/col1/{index}.jpg' width='100%'></div>";
var w = 1, h = 1, html = '', limitItem = 24;
for (var i = 0; i < limitItem; ++i) {
w = 1 + 3 * Math.random() << 0;
html += temp.replace(/\{width\}/g, w*150).replace("{index}", i + 1);
}
$("#freewall").html(html);
var wall = new Freewall("#freewall");
wall.reset({
selector: '.brick',
animate: true,
cellW: 150,
cellH: 'auto',
onResize: function() {
wall.fitWidth();
}
});
var images = wall.container.find('.brick');
images.find('img').load(function() {
wall.fitWidth();
});
</script>
</div>
Images may not appear when I put the tag href
var temp = "<div class='brick' style='width:{width}px;'><a href='img/col1/{index}.jpg'><img src='img/col1/{index}.jpg' width='100%'></a></div>";
Appears the link, but not the images.
Any help I'm appreciate. Thanks
I think more easily you can do is.
.style1{
display:block;
width:100%;
}
add this class to your a tag
<a class="style1" href='img/col1/{index}.jpg'>
Hope that helps
Edited:
The problem seems here.
.replace("{index}", i + 1);
use this.
.replace("/{index}/g", i + 1);

how to set font size of exported table in jspdf.js?

I am using jspdf.debug.js to export pdf data from html page.Here is the function of controller that I am using. I made a string as html table that I want to export.
$scope.exportReport = function (fileName, fileType) {
objReport.count = 0; // for getting all records
ReportService.getSaleDetail(objReport).then(function (result) {
var strTable = "<table id='tableReport'><tr><td style='width:400px'>Date</td><td style='width:50px'>Order Id</td><td style='width:130px'>Product</td><td style='width:120px'>Gorss Price</td><td style='width:160px'>Currency</td><td style='width:50px'>Order Status</td><td style='width:150px'>Assigned To</td><td style='width:150px'>Assigned User Email</td><td style='width:150px'>Country</td></tr>";
var strRow = '';
if (result.data.totalRecords > 0) {
var totalRecords = parseInt(result.data.totalRecords);
var saleDataJson = result.data.saleDetail;
for (var i = 0; i < totalRecords; i++) {
strRow = '<tr><td>' + saleDataJson[i].date + '</td>' + '<td>' + saleDataJson[i].orderId + '</td>' + '<td>' + saleDataJson[i].product + '</td>' + '<td>' + (1 * saleDataJson[i].grossPrice).toFixed(2) + '</td>' + '<td>' + saleDataJson[i].currency + '</td>' + '<td>' + saleDataJson[i].orderStatus + '</td>' + '<td>' + saleDataJson[i].assignedTo + '</td><td>' + saleDataJson[i].assignedUserEmail + '</td><td>' + saleDataJson[i].country + '</td></tr>';
strTable += strRow;
}
strTable += "</table>";
}
if (fileType === 'pdf') {
var pdf = new jsPDF('p', 'pt', 'letter') // jsPDF(orientation, unit, format)
, source = strTable
, specialElementHandlers = {
// element with id of "bypass" - jQuery style selector
'#bypassme': function (element, renderer) {
// true = "handled elsewhere, bypass text extraction"
return true;
}
},
margins = {
top: 30,
bottom: 40,
left: 35,
width: 600
};
pdf.setFontSize(12);
pdf.text(200, 30, fileName);
pdf.setFontSize(8);
pdf.setFontStyle('italic');
pdf.text(420, 35, 'Total Records : ' + totalRecords);
pdf.fromHTML(
source // HTML string or DOM elem ref.
, margins.left // x coord
, margins.top // y coord
, {
'width': margins.width // max width of content on PDF
, 'elementHandlers': specialElementHandlers
},
function (dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
pdf.save(fileName + '.pdf');
},
margins
)
}
});
};
and this method is exporting pdf file like this
I tried style with tang but it is not working
How can lower the font size so that i can export pdf file properly ?
pdf.setFont("helvetica");
pdf.setFontType("bold");
pdf.setFontSize(9);
it seems that pdf.fromHTML on tables ignores styling, or even jsPdf settings, such as pdf.setFont("helvetica"); etc.
so you can make changes to the original jspdf.debug.js file:
a) default autoSize is false, so you may change it.
b) default fontSize is 12 - you should senthe d smaller value (add your value to the last argument).
/*** TABLE RENDERING ***/
} else if (cn.nodeName === "TABLE") {
table2json = tableToJson(cn, renderer);
renderer.y += 10;
renderer.pdf.table(renderer.x, renderer.y, table2json.rows, table2json.headers, {
autoSize : true,
printHeaders : true,
margins : renderer.pdf.margins_doc,
fontSize : 9
});
}
I give you an example that works for me:
function imprimirPdf() {
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.setFont("arial", "bold");
pdf.setFontSize(14);
pdf.text(20, 20, 'Consulta');
$("#idTablaDatos").css("font-size", "10px");// change property value
$("#idTablaDetalle").css("font-size", "10px");// change property value
source = $('#div_pdf').html();//div_pdf contains idTablaDatos and idTablaDetalle
$("#idTablaDatos").css("font-size","14px");// original value
$("#idTablaDetalle").css("font-size","14px");// original value
specialElementHandlers = {
'#bypassme': function (element, renderer) {
return true
}
};
margins = {
top: 80,
bottom: 60,
left: 40,
width: 522
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(
source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, {// y coord
'width': margins.width, // max width of content on PDF
'elementHandlers': specialElementHandlers
},
function (dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
pdf.save('Test.pdf');
}, margins);
}
This works for me:
table.style.fontSize = '5px';
Try AutoTable - Table plugin for jsPDF
<a class="pull-right btn btn-warning btn-large" href="#" onclick="generate();"><i class="fa fa-file-excel-o"></i> PDF Data</a>
<table class="table table-bordered table-striped" id="basic-table">
<script src='https://cdn.rawgit.com/simonbengtsson/jsPDF/requirejs-fix-dist/dist/jspdf.debug.js'></script>
<script src='https://unpkg.com/jspdf-autotable#2.3.2'></script>
<script src="<?php echo base_url();?>assets/bower_components/jspdf/dist/index.js"></script>
<script>
function generate() {
var doc = new jsPDF('l', 'pt', 'a4');
doc.setFontSize(12);
var res = doc.autoTableHtmlToJson(document.getElementById("basic-table"));
doc.autoTable(res.columns, res.data, {margin: {top: 80}});
var header = function(data) {
doc.setFontSize(18);
doc.setTextColor(40);
doc.setFontStyle('normal');
//doc.addImage(headerImgData, 'JPEG', data.settings.margin.left, 20, 50, 50);
doc.text("Country List", data.settings.margin.left, 50);
};
var options = {
beforePageContent: header,
margin: {
top: 80
},
startY: doc.autoTableEndPosY() + 20
};
doc.autoTable(res.columns, res.data, options);
doc.save("Test.pdf");
}
</script>
Simple and direct:
var doc = new jspdf.jsPDF();
doc.autoTable({ html: '#tabelaDadosExtrato' });
doc.save('extrato-cliente-bet.pdf');
Based on example in https://github.com/simonbengtsson/jsPDF-AutoTable

Fix node width and height in Spacetree from Javascript Infovis Toolkit

I've finally got my nodes almost done perfectly, unfortunately I'm having one more problem
the width of what is drawn on the canvas isn't the width of the defined node. The blue + purple is the node div + padding, and I could perfectly center it using that if it weren't for the fact that what is drawn doesn't care about the width I have for that. Here's my code for my spacetree:
function jitSpaceTree(data,index,rootid){
var json = eval("(" + data + ")");
console.log(json);
//end
//init Spacetree
//Create a new ST instance
var st = new $jit.ST({
//id of viz container element
injectInto: 'hier'+index,
//set duration for the animation
duration: 800,
//set animation transition type
transition: $jit.Trans.Quart.easeInOut,
//set distance between node and its children
levelDistance: 25,
orientation: 'top',
//enable panning
Navigation: {
enable:true,
panning:true
},
//set node and edge styles
//set overridable=true for styling individual
//nodes or edges
Node: {
autoHeight: true,
autoWidth: true,
type: 'rectangle',
color: '#aaa',
overridable: true
},
Edge: {
type: 'bezier',
overridable: true
},
//This method is called on DOM label creation.
//Use this method to add event handlers and styles to
//your node.
onCreateLabel: function(label, node){
label.id = node.id;
label.innerHTML = node.name;
label.onclick = function(){
st.onClick(node.id);
st.select(node.id);
st.removeSubtree(label.id, false, "replot", {
hideLabels: false
});
jQuery.getJSON('Mobile_Subordinate.cfm?Empid='+node.id, function(data2) {
var subtree = '';
for(var i=0; i<data2.DATA.length-1; i++){
subtree = subtree + '{"id": "' + data2.DATA[i][4].replace(/\s/g, '') + '","name": "' + data2.DATA[i][0].replace(/\s/g, '') + '<br>' + data2.DATA[i][1].replace(/\s/g, '') + '","data": {},"children": []},';
}
subtree = subtree + '{"id": "' + data2.DATA[data2.DATA.length-1][4].replace(/\s/g, '') + '","name": "' + data2.DATA[data2.DATA.length-1][0].replace(/\s/g, '') + '<br>' + data2.DATA[data2.DATA.length-1][1].replace(/\s/g, '') + '","data": {},"children": []}';
subtree = '{"id": "'+label.id+'", "children": ['+ subtree +']}'
childData = jQuery.parseJSON(subtree);
console.log(childData);
st.addSubtree(childData, 'replot',{
hideLabels: false
});
});
};
//set label styles
var style = label.style;
style.width = node.data.offsetWidth;
style.height = node.data.offsetHeight;
style.cursor = 'pointer';
style.color = '#fff';
style.fontSize = '0.8em';
style.textAlign= 'center';
},
//This method is called right before plotting
//a node. It's useful for changing an individual node
//style properties before plotting it.
//The data properties prefixed with a dollar
//sign will override the global node style properties.
onBeforePlotNode: function(node){
//add some color to the nodes in the path between the
//root node and the selected node.
if (node.selected) {
node.data.$color = "#ab8433";
}
else {
delete node.data.$color;
node.data.$color = "#ccc";
}
},
//This method is called right before plotting
//an edge. It's useful for changing an individual edge
//style properties before plotting it.
//Edge data proprties prefixed with a dollar sign will
//override the Edge global style properties.
onBeforePlotLine: function(adj){
if (adj.nodeFrom.selected && adj.nodeTo.selected) {
adj.data.$color = "#eed";
adj.data.$lineWidth = 3;
}
else {
delete adj.data.$color;
delete adj.data.$lineWidth;
}
}
});
//load json data
st.loadJSON(json);
//compute node positions and layout
st.compute();
//optional: make a translation of the tree
st.geom.translate(new $jit.Complex(-200, 0), "current");
//emulate a click on the root node.
//st.onClick(st.root);
st.onClick(rootid);
//end
}
What am I missing?
Not an exact answer but could this be a padding issue?
I know from my own experience that
Node: {
height: 80,
width: 140
}
needs...
{style.width = 136 + 'px';
style.height = 75 + 'px';
style.paddingTop = '5px';
style.paddingLeft = '2px';
style.paddingRight = '2px';}
to center align.
I wonder if there is a default padding you're missing?

Categories