Custom node: chart in my editor

I SOLVED IT!!!

The mistake that I made was actually really simple. I did not link the chart.js code in my settings file using httpStatic, but I solved that problem with this (Import JavaScript library into node-red) post.

So the httpStatic thing is very easy to do:

  1. create a directory with a beautiful name, like C:/node-red-static/chartjs and put your Chart.js files here
  2. go to your .node-red folder and open settings.js, set httpStatic to C:/node-red-static
  3. restart node-red
  4. load http://localhost:1880/chartjs/dist/Chart.js, you should see your Chart.js code here

In your html code link Chart.js using

<script src="http://localhost:1880/chartjs/dist/Chart.js"></script>

and my total html code is shown below. I hope this can help someone!

<script src="http://localhost:1880/chartjs/dist/chart.js"></script>
<script type="text/javascript">
	RED.nodes.registerType('test-chart',{
		category: 'test',
		color: '#a6bbcf',
		defaults: {
			name: {value:""},
			someProps: {value:0}
		},
		inputs:1,
		outputs:1,
		label: function(){ return this.name || 'test-chart';},
		oneditprepare: function(){
			var canvas = document.getElementById("myChart");
			var ctx = canvas.getContext("2d");
			//ctx.font = "30px Verdana";
			//ctx.fillStyle = "red";
			//ctx.textAlign = "center";
			//ctx.fillText("Hello World!", canvas.width/2, canvas.height/2);
			var myChart = new Chart(ctx, {
				type: 'bar',
				data: {
					labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
					datasets: [{
						label: '# of Votes',
						data: [12, 19, 3, 5, 2, 3],
						backgroundColor: [
							'rgba(255, 99, 132, 0.2)',
							'rgba(54, 162, 235, 0.2)',
							'rgba(255, 206, 86, 0.2)',
							'rgba(75, 192, 192, 0.2)',
							'rgba(153, 102, 255, 0.2)',
							'rgba(255, 159, 64, 0.2)'
						],
						borderColor: [
							'rgba(255, 99, 132, 1)',
							'rgba(54, 162, 235, 1)',
							'rgba(255, 206, 86, 1)',
							'rgba(75, 192, 192, 1)',
							'rgba(153, 102, 255, 1)',
							'rgba(255, 159, 64, 1)'
						],
						borderWidth: 1
					}]
				},
				options: {
					scales: {
						yAxes: [{
							ticks: {
								beginAtZero: true
							}
						}]
					}
				}
			});
		}
	});
</script>

<script type="text/x-red" data-template-name="test-chart">
	<div id="test-chart">
	<canvas id="myChart" width="400" height="400"></canvas>
	</div>
</script>

<script type="text/x-red" data-help-name="test-chart">
	<p> helup </p>
</script>
1 Like