Using Datalabels and ChartJS with Chartjs-node-canvas - node.js

I use NodeJS with ChartJS to render graph directly to a file and it works fine.
I do it by ChartjsNodeCanvas npm module installed.
In order to display labels on the graph I use official ChartJS plugin ChartJS-plugin-datalabels
But it seems like Canvas module has a different scheme of activating ChartJS plugins and most probably I activate datalabels plugin incorrectly. So I can’t get the labels displayed on the graph.
const Chart = require('chart.js');
const datalabels = require('chartjs-plugin-datalabels')
const { CanvasRenderService } = require('chartjs-node-canvas');
const width = 600;
const height = 400;
const chartCallback = (ChartJS) => {
ChartJS.defaults.global.elements.rectangle.borderWidth = 2;
ChartJS.plugins.register({
datalabels
});
};
const canvasRenderService = new CanvasRenderService(width, height, chartCallback);
(async () => {
const configuration = {
type: 'bar',
data: {
datasets: [
{
type:"bar",
barThickness: 24,
label: 'My dataset',
data: ydata['data'],
backgroundColor: 'rgba(75,192, 192, 0.2)',
borderColor: 'rgba(54, 162, 135, 0.2)',
borderWidth: 1,
datalabels: {
align: 'start',
anchor: 'start'
}
},
labels: xdata,
}
options: {
scales: {
yAxes: [
{
id: 'left-y-axis',
position: 'left',
stacked: false,
ticks: {
beginAtZero: true,
callback: (value) => value + "R"
},
},
{
id: 'right-y-axis',
position: 'right'
}
],
xAxes: [{
stacked: true,
}]
},
plugins: {
datalabels: {
backgroundColor: function(context) {
return context.dataset.backgroundColor;
},
borderRadius: 4,
color: 'red',
font: {
weight: 'bold'
},
formatter: Math.round
}
}
}
};
const image = await canvasRenderService.renderToBuffer(configuration);
fs.writeFileSync(tgMsgPath+"test.png", image)
})();
The chart is shown but no labels on the graph.

This is how to activate plugins with ChartJs-niode-canvas:
const chartJsFactory = () => {
const Chart = require('chart.js');
require('chartjs-plugin-datalabels');
delete require.cache[require.resolve('chart.js')];
delete require.cache[require.resolve('chartjs-plugin-datalabels')];
return Chart;
}
// ...
const canvasRenderService = new CanvasRenderService(
chartWidth,
chartHeight,
chartCallback,
undefined,
chartJsFactory
);

Related

How to remove geoJSON shape stroke in Leaflet?

The situation is that of the image:
This is the code (see click event):
private initRegionsLayer() {
const layer = new GeoJSON(this.regions, {
style: (feature) =>
this.styleService.regionsStyleMaker(feature, this.data, this.type),
onEachFeature: (feature, layer) => {
layer.on({
mouseover: (e) =>
this.highlightShapeService.highlightShape(e, feature, this.data),
mouseout: (e) => this.highlightShapeService.resetShape(e),
click: (e) => {
e.target.setStyle({
stroke: false,
})
},
});
const foundRecord = this.data.find(
(item: { regione: any }) =>
feature.properties['Regione'] === item.regione
);
if (foundRecord) {
layer.bindTooltip(this.popupService.regionsPopup(foundRecord), {
direction: 'right',
permanent: false,
sticky: true,
offset: [20, 0],
opacity: 0.9,
});
}
},
});
Even if I try to set "stroke" to "false", nothing happens.
How to solve? Thanks!

how to set character frame of spritesheet in phaser js?

how to set frame of character?
here is my code
this.load.spritesheet(`dude-1`, `../src/assets/Character/ch-1.png`, {
frameWidth: 72,
frameHeight: 92,
});
main logic code is here
this.player = this.physics.add.sprite(100, -500, this.charSelect).setOrigin(1, 1);
this.player.body.setGravityY(1700);
this.player.setBounce(0.1);
this.physics.add.existing(this.player).body.setSize(15, 90, ).setOffset(20, 0)
this.anims.create({
key: "left",
frames: this.anims.generateFrameNumbers(this.charSelect, { start: 6, end: 10 }),
frameRate: 10,
repeat: -1,
});
this.anims.create({
key: "turn",
frames: [{ key: this.charSelect, frame: 5 }],
frameRate: 10,
});
this.anims.create({
key: "right",
frames: this.anims.generateFrameNumbers(this.charSelect, { start: 0, end: 4 }),
frameRate: 10,
repeat: -1,
});
cursors = this.input.keyboard.createCursorKeys();
this.physics.add.collider(this.player, this.platformGroup);
this.player.body.setCollideWorldBounds(true);
this.physics.world.setBounds(0, 0, (config.width) - 10, config.height, true, true, false, true);
here is output and issue. how to set the frame of character?
The problem is, that the phaser-image / frame size is too big (or the actual image is to small). Check the frame size (frameWidth and frameHeight) and the actual image size, that could solve your problem.
Here a short demo:
It loads the same spritesheet, once with the correct frameWidth / frameHeight size and once with a too big size.
document.body.style = `padding:0;margin:0;`;
class Example extends Phaser.Scene {
constructor() {
super();
}
preload() {
this.load.spritesheet('mummyCorrectSize', 'https://labs.phaser.io/assets/animations/mummy37x45.png', { frameWidth: 37, frameHeight: 45 });
this.load.spritesheet('mummyWrongSize', 'https://labs.phaser.io/assets/animations/mummy37x45.png', { frameWidth: 50, frameHeight: 50 });
}
create(){
// the "const" variables show the the wrong and right sprite creation
const wrongSizeSprite= this.add.sprite(50, 40, 'mummyCorrectSize').setOrigin(0);
const rightSizeSprite = this.add.sprite(50, 120, 'mummyWrongSize').setOrigin(0);
this.add.text(50, 10, 'Right size: single sprite/frame shown');
this.add.text(50, 100, 'Wrong size: the whole image is shown');
}
}
const config = {
type: Phaser.AUTO,
width: 500,
height: 180,
scene: [ Example ]
};
new Phaser.Game(config);
<script src="//cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

JointJS - How to change colour of remove link icon

In JointJS the remove link SVG that appears is a red circle with a white X in it. I would like to change the colour of the red circle for all remove link icons. Anyone know how to do this?
Thanks!
Tried reading the following but couldn't find what I wanted:
https://resources.jointjs.com/demos/kitchensink
I want to do something like this:
defaultLink: new joint.shapes.app.Link({
attrs: {
remove: {
circle: {
fill: '#634ee9'
}
}
}
}),
I want the red 'remove link' circle to change to a blue/purple one
You can implement your own remove button
this.paper.on({
'link:mouseenter': function (linkView) {
linkView.addTools(new joint.dia.ToolsView({
tools: [
new joint.linkTools.Vertices({ snapRadius: 0 }),
new joint.linkTools.Remove({
distance: 20
}),
new joint.linkTools.Button({
markup: [{
tagName: 'circle',
selector: 'button',
attributes: {
'r': 15,
'stroke': '#fe854f',
'stroke-width': 1,
'fill': 'white',
'cursor': 'pointer'
}
}, {
tagName: 'text',
textContent: 'X',
selector: 'icon',
attributes: {
'fill': '#fe854f',
'font-size': 8,
'text-anchor': 'middle',
'font-weight': 'bold',
'pointer-events': 'none',
'y': '0.3em'
}
}],
distance: -50,
action: function () {
var link = this.model;
link.remove();
}
})
]
}));
}
})

can't get data-labels in highcharts-export-server on live server

i am using highcharts-export-server for export charts and send it to Email in PDF format
while i am trying to export that in localy it was working fine, but on live server when i am trying to export all the charts data-labels disappear.
this is the image from which was exporting from live server.
and here is the image which was exporting locally.
Here is my Code
exports.getPieChartImg = (seriesData, xOrLength, innersize, showLegend, width, height) => {
var chartOpts = {
chart: {
type: 'pie',
width: width,
height: height,
},
plotOptions: {
pie: {
innerSize: innersize || 80,
depth: 25,
allowPointSelect: true,
dataLabels: {
enabled: false,
format: '<b>{point.name}</b>: {point.percentage:.2f} %'
},
showInLegend: showLegend || false,
},
series: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: '#6f6f6f',
format: '{point.percentage:.2f}',
crop: false,
overflow: "none",
},
pointWidth: 30,
}
},
legend: {
labelFormat: '<b>{name}</b> ({percentage:.2f})%',
useHTML: true,
},
series: [{
data: seriesData
}]
};
var exportSettings = generateExportSettings(chartOpts, 'Pie');
return generateBase64Chart(exportSettings)
}
function generateExportSettings(chartOpts, constr) {
return {
// b64: true,
instr: JSON.stringify(chartOpts),
noDownload: true,
constr,
globalOptions: {
colors: ['#3BB9DA', '#0F89A8', '#0B8F8B', '#1DB1AD', '#68E3DF', '#FFB469', '#F58B1F', '#D16900', '#FC3C3C', '#FF6666', '#FC8D8D', '#FCC0C0'],
lang: {
thousandsSep: ','
}
},
scale: false,
styledMode: false,
type: "image/png",
width: false,
};
}
function generateBase64Chart(exportSettings) {
return new Promise((resolve, reject) => {
highchartsExporter.export(exportSettings, function (err, res) {
if (err) {
return reject({
code: '1',
err,
msg: 'Error in stock chart',
exportSettings
})
}
return resolve({
code: '0',
msg: 'success',
data: 'data:image/png;base64,' + res.data,
})
});
})
}
remove node_module and reInstall it again.
and if not installed libfontconfig then install 'sudo apt-get install libfontconfig'

get svg code in highchart directive with angular js

in normal highchart i get svg code with code like this
var chart = $('#container').highcharts()
svg = chart.getSVG();
So, how can i get svg code with this highchart directive in angular js???
i try like normal code but i didn't get svg code.
i use this directive for my highchart
https://github.com/rootux/angular-highcharts-directive
and this my code in controller.js
$scope.chartLogisticGIGR = {
options: {
tooltip: {
shared: true
}
},
xAxis: { // Primary xAxis
categories: $scope.nameMonths,
title: {
text: 'Month'
},
labels: {
enabled: true
},
min:0
},
yAxis: [{ // Primary yAxis
title: {
text: 'GI / GR in IDR'
},
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value / 1000000,'0') + ' mil';
}
}
}, { // Secondary yAxis
title: {
text: 'Balance'
},
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value / 1000000,'0') + ' mil';
}
},
}],
series: [{
name: 'AGP - Goods Receipt',
type: 'column',
stacking: 'normal',
stack: '1',
data: $scope.dataLogisticGIGR_AGP_GR,
color: $rootScope.getColor('AGP Ext'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AGP - Goods Issue',
type: 'column',
stacking: 'normal',
stack: '1',
data: $scope.dataLogisticGIGR_AGP_GI,
color: $rootScope.getColor('AGP Int'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AGP - Balance',
type: 'spline',
data: $scope.dataLogisticGIGR_AGP_Balance,
color: $rootScope.getColor('AI 2'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AI - Goods Receipt',
type: 'column',
stacking: 'normal',
stack: '3',
data: $scope.dataLogisticGIGR_AI_GR,
color: $rootScope.getColor('AI'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AI - Goods Issue',
type: 'column',
stacking: 'normal',
stack: '3',
data: $scope.dataLogisticGIGR_AI_GI,
color: $rootScope.getColor('AP 2'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AI - Balance',
type: 'spline',
data: $scope.dataLogisticGIGR_AI_Balance,
color: $rootScope.getColor('AP'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
}],
title: {
text: ''
},
loading: false
};
in this is my code in directive highchart
'use strict';
angular.module('chartsExample.directives',[])
.directive('chart', function () {
return {
restrict: 'E',
template: '<div></div>',
scope: {
chartData: "=value"
},
transclude:true,
replace: true,
link: function (scope, element, attrs) {
var chartsDefaults = {
chart: {
renderTo: element[0],
type: attrs.type || null,
height: attrs.height || null,
width: attrs.width || null
}
};
//Update when charts data changes
scope.$watch(function() { return scope.chartData; }, function(value) {
if(!value) return;
// We need deep copy in order to NOT override original chart object.
// This allows us to override chart data member and still the keep
// our original renderTo will be the same
var newSettings = {};
angular.extend(newSettings, chartsDefaults, scope.chartData);
var chart = new Highcharts.Chart(newSettings);
});
}
};
});
Thank's....

Resources