SoFunction
Updated on 2025-03-10

JS uses canvas technology to mimic echarts bar charts

canvas canvas is a new tag added in html5. You can draw images in web pages through the js operation canvas drawing API.

Baidu has developed an open source visual chart library ECharts, which has very powerful functions and can implement line charts, bar charts, scatter charts, pie charts, K-line charts, maps and other charts. Many projects have used ECharts to develop charting functions.

This example tutorial uses native js to teach you how to develop a bar chart that mimics ECharts. Before studying this tutorial, readers need to have html and css skills, and also need to have a simple JavaScript foundation.

According to the development method of ECharts, the charts are generated in an HTML element. Therefore, in this example, a div element with id name canvasWrap is prepared, as shown below:

<div class="canvas_wrap" ></div>

Then create the canvas element in the canvasWrap element, and then draw the bar chart on the canvas element. Before development, according to convention, it is better to analyze the specific operations of the bar chart first, and then divide the method of implementing functions into multiple steps according to the specific operations, and then complete it step by step.

1. Write bar chart data
2. Get the canvasWrap element and width and height
3. Create a drawing environment
3.1 Creating a canvas canvas
3.2 Set the width and height of the canvas canvas
3.3 Put the canvas canvas into the canvasWrap element
3.4 Creating a drawing context environment
4. Set the coordinate area
5. Draw the x-axis
5.1 Draw the axis
5.2 Drawing ticks
5.3 Draw the scale name
6. Draw the y-axis
6.1 Draw the axis
6.2 Drawing ticks
6.3 Drawing the scale value
6.4 Drawing x-axis grid lines
7. Draw a column chart
7.1 Calculate the bar chart width
7.2 Calculate the bar chart height
7.3 Calculate the starting point of bar chart X
7.4 Calculate the starting point of the bar chart Y
7.5 Drawing column charts

The specific code is as follows:

//1 Write bar chart dataoption = {
  //x-axis data  xAxis: {
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  //Bar chart data  series: [{
    //Write more sets of data to view the graph effect when different data    // data: [0.01, 0.2, 0.05, 0.07, 0.04, 0.13, 0.9],
    // data: [1, 1, 5, 7, 4, 1, 9],
    // data: [1213, 30, 150, 80, 70, 910, 630],
    data: [120, 199, 150, 180, 70, 110, 130],
    //Graphic style: column chart    type: 'bar'
  }]
};

//Create a chart function, wrap: chart parent element id; data: chart datafunction fnCharts(wrap,data){
  //2. Get the canvasWrap element  var eWrap = (wrap);
  //2. Get the width and height of the canvasWrap element, used to set the canvas canvas size  var nWrapW = ;
  var nWrapH = ;

  //3.1 Create canvas canvas  var eCanvas = ('canvas');
  //3.2 Set the width and height of the canvas canvas   = nWrapW;
   = nWrapH;
  //3.3 Put the canvas canvas into the canvasWrap element  (eCanvas);
  //3.4 Create a drawing context (to be able to draw on the Canvas canvas)  var oCtx = ('2d');

  //4. Set the upper left corner and lower right corner of the coordinate area  //The starting point is set to 50.5, not an integer, to make the lines clear  var nZoneStartX = 50.5;
  var nZoneStartY = 50.5;
  var nZoneEndX = nWrapW - nZoneStartX;
  var nZoneEndY = nWrapH - nZoneStartY;

  //5.1 Draw the x-axis axis using line functions  fnCreatLine(nZoneStartX,nZoneEndY,nZoneEndX,nZoneEndY);
  // Calculate the x-axis length  var nLonX = nZoneEndX - nZoneStartX;
  //Get the x-axis data array length  var nDataLon = ;
  //Collapse according to the length of the x-axis data array, draw the tick marks and tick value names in the loop  for(let i=0;i&lt;nDataLon;i++){
    // Calculate the value of the starting point of the x-axis tick mark on the x-axis    let nScaleX = nZoneStartX+(nLonX*(i/nDataLon));
    //The starting points of the ticks are on the x-axis    let nScaleY = nZoneEndY;
    //5.2 Draw ticks with length 10    fnCreatLine(nScaleX,nScaleY,nScaleX,nScaleY+10);
    //Get the tick name string from the data    let sName = [i];
    // Calculate the starting point of the scale name    let nNameX = nZoneStartX+(nLonX*(i/nDataLon))+(nLonX*(1/nDataLon))/2;
    let nNameY = nZoneEndY+15;
    //5.3 Draw the scale name    fnCreatText(sName,nNameX,nNameY,'#aaa','center');
  }

  //6.1 Draw the y-axis axis using line functions  fnCreatLine(nZoneStartX,nZoneEndY,nZoneStartX,nZoneStartY);
  //Before drawing a y-axis tick mark, you need to have the data such as the maximum tick value, the minimum value, the number of tick segments, and the interval between the tick marks.  //The maximum value of the scale is taken from the array first, and then calculate the maximum value that should be displayed later  var nMaxScal =  (null,[0].data);
  //The minimum scale value is taken 0 in this example  var nMinScal = 0;
  //The number of tick segments is set to 4 in this example  var nSplit = 4;
  // Calculate the scale interval value  var nStep = (nMaxScal-nMinScal)/nSplit;
  //At this time, you will find that the scale interval value seems a bit strange, because the scale interval value of the general chart is multiple of 5.  //For example: [0,0.5,1.0,1.5,2] or [0,50,100,150,200].  //So further calculation is needed to see if nStep is a multiple of 5. If not, increment nIncrease so that it reaches the closest multiple of 5.  //The first step of calculation, calculate the multiple value according to nStep, which should be 0.5 or 50 or...  //In this example, the nStep value is converted into a string before processing (logarithm and exponents can also be calculated).  var sTemp = '' + nStep; //Convert nStep to string  //Declare a number that needs to be incremented, default is 1  var nIncrease = 1;
  //Declare a variable to solve the accuracy bug caused by multiplication of decimals  var nTempMultiple = 1;  

  //nIncrease takes the n power of 10, and calculate it by the following judgment  if(('.')==-1){
    //If nStep does not contain a decimal point, nIncrease takes a power of -2 of 10.    //For example, if nStep is 19, nIncrease = 0 power of 10, the increment number is 1    // If nStep is 9, nIncrease = 10's power of -1, the increment number is 0.1    // If nStep is 199, nIncrease = 10's power, and the increment number is 10    nIncrease = (10,-2);
  }else{
    //If nStep contains a decimal point, nIncrease takes sTemp integer of 10 -2 power.    nIncrease = (10,('.')-2);
    //This variable is used to solve the accuracy bugs that may occur when multiplying decimals, such as the case where nIncrease is a decimal    nTempMultiple = (10,('.')); 
  }
  //The multiple is rounded to facilitate incrementality. If 165 is changed to 160, 16.5 is changed to 16, and 1.65 is changed to 1.6, it can be achieved through the following formula  nStep = (nStep/nIncrease)*(nIncrease*nTempMultiple)/nTempMultiple;
  //Change nIncrease to correct the tick value using loop increment  while(nStep%(nIncrease*5)!=0){
    nStep += nIncrease*1;
  }
  //Modify the maximum value of the scale by multiplying the interval value by the number of line segments  nMaxScal = nStep * nSplit;
  // Calculate the length of the y-axis, and minus 3 more here because the point distance must be left at the top of the y-axis  var nLonY = nZoneEndY - nZoneStartY - 3;
  //Draw the y-axis scale  for(let i=0;i&lt;=nSplit;i++){
    //The starting points of the ticks are on the y-axis    let nScaleX = nZoneStartX;
    // Calculate the value of the starting point of the y-axis tick on the y-axis    let nScaleY = (nLonY*(i/nSplit));
    //6.2 Draw ticks    fnCreatLine(nScaleX,nScaleY,nScaleX-10,nScaleY);
    //6.3 Draw the scale value    fnCreatText(''+i*nStep,nScaleX-20,nScaleY,'#333');
    if(i!=0){
      //6.4 Non-0 position, draw x-axis grid lines      fnCreatLine(nScaleX,nScaleY,nScaleX+nLonX,nScaleY,'#ccc');
    }
  }

  //7.1 Calculate the bar chart width  let nBarWidth = ((nLonX*(1/nDataLon))*.8);
  //Transfer the x-axis data  for(let i=0;i&lt;nDataLon;i++){
    //7.2 Calculate the bar chart height    let nBarHeight = nLonY/nMaxScal*[0].data[i];
    //7.3 Calculate the starting point of bar chart X    let nBarStartX = nZoneStartX+(nLonX*(i/nDataLon))
                     +((nLonX*(1/nDataLon))-nBarWidth)/2;
    //7.4 Calculate the starting point of the bar chart Y    let nBarStartY = nZoneEndY-nBarHeight;
    //7.5 Draw a column chart    fnCreatRect(nBarStartX,nBarStartY,nBarWidth,nBarHeight);
  }

  //Draw line function  function fnCreatLine(sX,sY,eX,eY,color='#000'){
    //Start drawing path    ();
    //Set the path color     = color;
    //Set the starting point and end point of the path and draw lines    (sX,sY);
    (eX,eY);
    //Add color to the path    ();
  }

  //Draw text  function fnCreatText(text,x,y,color='#000',align='end',baseLine='middle'){
    //Set text color     = color;
    //Set horizontal alignment     = align;
    //Set vertical alignment     = baseLine;
    //Draw text    (text,x,y);
  }

  //Draw rectangle  function fnCreatRect(x,y,width,height,color='#a00'){
    //Set the color     = color;
    (x,y,width,height);
  }
}
//Call the chart function and pass in the element id and option datafnCharts('canvasWrap',option);

This example tutorial may require some patience to read the source code. If you encounter something you don’t understand, you can output the value at the source code location you don’t understand, and you may suddenly become clear.

The above is the detailed content of JS using canvas technology to imitate echarts bar charts. For more information about JS using canvas bar charts, please pay attention to my other related articles!