Comment créer des barres arrondies pour Bar Chart.js v2?

Essayer de contourner les barres sur le graphique à barres comme on le trouve dans ce post qui fonctionne comme indiqué dans le jsFiddle fourni. Ceci est pour la version 1.

Dans le graphique que j’utilise, le chargement échoue pour que la référence extend dans Chart.types.Bar.extend le script.

Si j’utilise l’option par défaut, le graphique ne charge aucun problème. Je devais placer le Chart.types.Bar.extend à la fin pour que l’option par défaut se charge correctement. Exécuter et afficher ceci en plein écran.

J’ai essayé d’implémenter ceci avec ma version de Chart.js 2.4.0.

Rapports Chrome:

Uncaught TypeError: impossible de lire la propriété ‘extend’ de undefined chart.js

Ce code ne sera même pas exécuté ici. Pourquoi cela se produit-il? Quelqu’un pourrait-il m’aider s’il vous plaît.

Ce code fonctionne avec une version plus ancienne de Chart.js 1.0. Quelqu’un pourrait-il s’il vous plaît afficher davantage comment cela pourrait fonctionner avec la version Chart.js 2.0? Je vous remercie.

 $(document).ready(function(){ var myBarChart1 = new Chart($('#appBarChart2_NoRound'), { type: 'bar', data: dataBar2, options: optionsBar }); var ctx = $("#appBarChart2").getContext("2d"); var myBarChart2 = new Chart(ctx).BarAlt(dataBarAlt2, { // 0 (flat) to 1 (more curvy) curvature: 1 }); }); var dataBarAlt2 = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { fillColor: "#1A9BFC", strokeColor: "#1A9BFC", data: [65, 59, 80, 81, 56, 55, 40], } ] }; var dataBar2 = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: "My First dataset", backgroundColor: '#1A9BFC', borderColor:'#1A9BFC', borderWidth: 1, data: [65, 59, 80, 81, 56, 55, 40], } ] }; var optionsBar = { scales: { xAxes: [{ stacked: true, barThickness: 20, gridLines:{ display:false, } // barPercentage:0.5, }], yAxes: [{ stacked: true, // barPercentage:0.5, }] }, legend: { display: false, // position: 'left' } }; Chart.types.Bar.extend({ name: "BarAlt", initialize: function (data) { Chart.types.Bar.prototype.initialize.apply(this, arguments); if (this.options.curvature !== undefined && this.options.curvature <= 1) { var rectangleDraw = this.datasets[0].bars[0].draw; var self = this; var radius = this.datasets[0].bars[0].width * this.options.curvature * 0.5; // override the rectangle draw with ours this.datasets.forEach(function (dataset) { dataset.bars.forEach(function (bar) { bar.draw = function () { // draw the original bar a little down (so that our curve brings it to its original position) var y = bar.y; // the min is required so animation does not start from below the axes bar.y = Math.min(bar.y + radius, self.scale.endPoint - 1); // adjust the bar radius depending on how much of a curve we can draw var barRadius = (bar.y - y); rectangleDraw.apply(bar, arguments); // draw a rounded rectangle on top Chart.helpers.drawRoundedRectangle(self.chart.ctx, bar.x - bar.width / 2, bar.y - barRadius + 1, bar.width, bar.height, barRadius); ctx.fill(); // restore the y value bar.y = y; } }) }) } } }); 
   

Bar Chart - Working

Rounded Bar Chart - Not Working

Le code que vous avez essayé d’utiliser est en fait pour chart.js v1 et, comme vous l’avez découvert, ne fonctionne pas pour chart.js v2 (qui est presque une réécriture complète de chart.js).

Pour obtenir les mêmes résultats dans chart.js v2, vous devez étendre Chart.elements.Rectangle et écraser sa méthode de draw afin de peindre le sumt arrondi. Il existe déjà une méthode d’assistance chart.js qui dessine un rectangle arrondi ( Chart.helpers.drawRoundedRectangle ). Nous allons donc le modifier légèrement et créer une nouvelle méthode d’assistance qui dessinera uniquement un sumt arrondi (au lieu de tous les côtés).

 // draws a rectangle with a rounded top Chart.helpers.drawRoundedTopRectangle = function(ctx, x, y, width, height, radius) { ctx.beginPath(); ctx.moveTo(x + radius, y); // top right corner ctx.lineTo(x + width - radius, y); ctx.quadraticCurveTo(x + width, y, x + width, y + radius); // bottom right corner ctx.lineTo(x + width, y + height); // bottom left corner ctx.lineTo(x, y + height); // top left ctx.lineTo(x, y + radius); ctx.quadraticCurveTo(x, y, x + radius, y); ctx.closePath(); }; Chart.elements.RoundedTopRectangle = Chart.elements.Rectangle.extend({ draw: function() { var ctx = this._chart.ctx; var vm = this._view; var left, right, top, bottom, signX, signY, borderSkipped; var borderWidth = vm.borderWidth; if (!vm.horizontal) { // bar left = vm.x - vm.width / 2; right = vm.x + vm.width / 2; top = vm.y; bottom = vm.base; signX = 1; signY = bottom > top? 1: -1; borderSkipped = vm.borderSkipped || 'bottom'; } else { // horizontal bar left = vm.base; right = vm.x; top = vm.y - vm.height / 2; bottom = vm.y + vm.height / 2; signX = right > left? 1: -1; signY = 1; borderSkipped = vm.borderSkipped || 'left'; } // Canvas doesn't allow us to stroke inside the width so we can // adjust the sizes to fit if we're setting a stroke on the line if (borderWidth) { // borderWidth shold be less than bar width and bar height. var barSize = Math.min(Math.abs(left - right), Math.abs(top - bottom)); borderWidth = borderWidth > barSize? barSize: borderWidth; var halfStroke = borderWidth / 2; // Adjust borderWidth when bar top position is near vm.base(zero). var borderLeft = left + (borderSkipped !== 'left'? halfStroke * signX: 0); var borderRight = right + (borderSkipped !== 'right'? -halfStroke * signX: 0); var borderTop = top + (borderSkipped !== 'top'? halfStroke * signY: 0); var borderBottom = bottom + (borderSkipped !== 'bottom'? -halfStroke * signY: 0); // not become a vertical line? if (borderLeft !== borderRight) { top = borderTop; bottom = borderBottom; } // not become a horizontal line? if (borderTop !== borderBottom) { left = borderLeft; right = borderRight; } } // calculate the bar width and roundess var barWidth = Math.abs(left - right); var roundness = this._chart.config.options.barRoundness || 0.5; var radius = barWidth * roundness * 0.5; // keep track of the original top of the bar var prevTop = top; // move the top down so there is room to draw the rounded top top = prevTop + radius; var barRadius = top - prevTop; ctx.beginPath(); ctx.fillStyle = vm.backgroundColor; ctx.strokeStyle = vm.borderColor; ctx.lineWidth = borderWidth; // draw the rounded top rectangle Chart.helpers.drawRoundedTopRectangle(ctx, left, (top - barRadius + 1), barWidth, bottom - prevTop, barRadius); ctx.fill(); if (borderWidth) { ctx.stroke(); } // restore the original top value so tooltips and scales still work top = prevTop; }, }); 

Ensuite, vous devrez également étendre le contrôleur de graphique à barres ( Chart.controllers.bar ) et écraser dataElementType pour utiliser le nouveau “rectangle arrondi” pour le graphique au lieu d’un rectangle régulier.

 Chart.defaults.roundedBar = Chart.helpers.clone(Chart.defaults.bar); Chart.controllers.roundedBar = Chart.controllers.bar.extend({ dataElementType: Chart.elements.RoundedTopRectangle }); 

Enfin, nous allons modifier la configuration du graphique pour utiliser le nouveau type de graphique créé ci-dessus et append une nouvelle propriété d’options appelée barRoundness pour contrôler le barRoundness du sumt (0 est plat, 1 est un demi-cercle).

 var ctx = document.getElementById("canvas").getContext("2d"); var myBar = new Chart(ctx, { type: 'roundedBar', data: { labels: ["Car", "Bike", "Walking"], datasets: [{ label: 'Students', backgroundColor: chartColors.blue, data: [ randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), ] }, { label: 'Teachers', backgroundColor: chartColors.red, data: [ randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), ] }, { label: 'Visitors', backgroundColor: chartColors.green, data: [ randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), ] }] }, options: { responsive: true, barRoundness: 1, title: { display: true, text: "Chart.js - Bar Chart with Rounded Tops (drawRoundedTopRectangle Method)" }, } }); 

Vous pouvez voir un exemple de travail complet à ce codepen .

De plus, si vous souhaitez un aspect légèrement différent du “sumt arrondi”, voici un autre codepen utilisant une approche différente pour dessiner le sumt (une seule courbe quadratique).