css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div class="b2b-graph-container">  
  <img alt="B2b index graph" class="b2b-graph" src="https://blog.coffeeandcode.com/wp-content/uploads/2017/10/b2b_index.jpg"/>
  <canvas data-aggregate="58" data-knowledge="14" data-interest="7" data-objectivity="6" data-foresight="11" data-concentration="20" id="graph-canvas"></canvas>
</div>
            
          
!
            
              .b2b-graph-container {
  position: relative;
  width: 100%;

  & .b2b-graph {
    width: 100%;
  }
}
            
          
!
            
              function drawGraph(global, container, canvas) {
  var barGraphElement = {
      maxAmount: 100,
      scoreAttribute: 'data-aggregate',
      width: 7.5,
      xCoord: 10.8,
      yScale: 10
    },
    lineGraphElementList = [
    {
      maxAmount: 20,
      scoreAttribute: 'data-knowledge',
      width: 1,
      xCoord: 37,
      yCoord: 0,
      yScale: 2
    }, {
      maxAmount: 20,
      scoreAttribute: 'data-interest',
      width: 1,
      xCoord: 49.1,
      yCoord: 0,
      yScale: 2
    }, {
      maxAmount: 20,
      scoreAttribute: 'data-objectivity',
      width: 1,
      xCoord: 62,
      yCoord: 0,
      yScale: 2
    }, {
      maxAmount: 20,
      scoreAttribute: 'data-foresight',
      width: 1,
      xCoord: 74.7,
      yCoord: 0,
      yScale: 2
    }, {
      maxAmount: 20,
      scoreAttribute: 'data-concentration',
      width: 1,
      xCoord: 87.5,
      yCoord: 0,
      yScale: 2
    }
  ],
  market_position = canvas.getAttribute('data-market-position'),
  universalDistanceFromTop = 20.87,
  canvasContainerOffsets = {};

  var calculateDistance = function calculateDistance(score, scale) {
    var distanceBetweenEachMarker = 6.2;

    return (score / scale) * distanceBetweenEachMarker;
  };

  var drawBarGraph = function drawBarGraph(context) {
    var currentItemScore = canvas.getAttribute(barGraphElement.scoreAttribute);

    context.beginPath();

    var distanceFromTop = calculateDistance(barGraphElement.maxAmount-currentItemScore, barGraphElement.yScale);
    var barHeight = calculateDistance(currentItemScore, barGraphElement.yScale);

    context.rect(getPixelWidthFromPercent(barGraphElement.xCoord),
      getPixelHeightFromPercent(universalDistanceFromTop + distanceFromTop),
      getPixelWidthFromPercent(barGraphElement.width),
      getPixelHeightFromPercent(barHeight));

    context.fill();
  };

  var drawLineGraphLine = function drawLineGraphLine(context, currentItem, previousItem) {
    if (!previousItem) {
      return;
    }

    context.beginPath();
    context.lineWidth = 4;

    context.moveTo(getPixelWidthFromPercent(previousItem.xCoord), getPixelHeightFromPercent(previousItem.yCoord));
    context.lineTo(getPixelWidthFromPercent(currentItem.xCoord), getPixelHeightFromPercent(currentItem.yCoord));

    context.stroke();
  };

  var drawLineGraphPoint = function drawLineGraphPoint(context, currentItem) {
      var currentItemScore = canvas.getAttribute(currentItem.scoreAttribute);
      // We  inverted the coordinates by subtracting it from the maximum since (0,0) is in the top left of the coordinate plane:
      var distanceFromTop = calculateDistance(currentItem.maxAmount-currentItemScore, currentItem.yScale);
      //Since the y distance is only the distance from the top of the plane to the value, we account for the  top buffer of space as well:
      currentItem.yCoord = universalDistanceFromTop + distanceFromTop;

      context.beginPath();

      context.arc(getPixelWidthFromPercent(currentItem.xCoord),
      getPixelHeightFromPercent(currentItem.yCoord),
      getPixelWidthFromPercent(currentItem.width),
      (Math.PI/180)*0,
      (Math.PI/180)*360,
      false);

      context.fill();
  };

  var drawOverallScore = function drawOverallScore(context) {
    context.font = getPixelWidthFromPercent(4) + "px Arial";
    context.fillText(canvas.getAttribute(barGraphElement.scoreAttribute), getPixelWidthFromPercent(49), getPixelHeightFromPercent(15.5));
  };

  var drawOverallScoreDescription = function drawOverallScoreDescription(context) {
    context.font = getPixelWidthFromPercent(2) + "px Arial";
    context.fillText(getScoreDescriptionFromScore(canvas.getAttribute(barGraphElement.scoreAttribute)), getPixelWidthFromPercent(54.7), getPixelHeightFromPercent(15));
  };

  var getPixelHeightFromPercent = function getPixelHeightFromPercent(percent) {
    return canvasContainerOffsets.height * (percent/100)
  };

  var getPixelWidthFromPercent = function getPixelWidthFromPercent(percent) {
    return canvasContainerOffsets.width * (percent/100)
  };

  var getScoreDescriptionFromScore = function getScoreDescriptionFromScore(score) {
    if (score >= 80) {
      return '(Intensely B2B)'
    } else if (score < 80 && score >= 60) {
      return '(Strongly B2B)'
    } else if (score < 60 && score >= 40) {
      return '(Moderately B2B)'
    } else if (score < 40 && score >= 20) {
      return '(Weakly B2B)'
    } else {
      return '(B2C)'
    }
  }

  var resize = function resize(event) {
    updateContainerOffsets();
  };

  var resizeAndPositionCanvas = function resizeAndPositionCanvas() {
    canvas.style.height = '100%';
    canvas.style.left = 0;
    canvas.style.position = 'absolute';
    canvas.style.top = 0;
    canvas.style.width = '100%';

    canvas.width  = canvas.offsetWidth;
    canvas.height = canvas.offsetHeight;
  };

  var updateContainerOffsets = function updateContainerOffsets() {
    var parentElement = container;

    canvasContainerOffsets = {
      height: parentElement.offsetHeight,
      width: parentElement.offsetWidth
    };
  }

  var initializeDrawing = function initializeDrawing() {
    var context = canvas.getContext('2d');

    resizeAndPositionCanvas(canvas);
    updateContainerOffsets();

    switch(market_position) {
      case 'none':
        context.fillStyle = '#21409a';
        context.strokeStyle = 'rgba(33,64,154,0.5)';
        break;
      case 'weak':
        context.fillStyle = '#009a4e';
        context.strokeStyle = 'rgba(0,154,78,0.5)';
        break;
      case 'strong':
        context.fillStyle = '#f7941e';
        context.strokeStyle = 'rgba(255,127,0,0.5)';
        break;
      case 'leader':
        context.fillStyle = '#ed1c24';
        context.strokeStyle = 'rgba(255,0,0,0.5)';
        break;
    }

    //Draw the overall score
    drawOverallScore(context);
    drawOverallScoreDescription(context);

    // Draw the bar graph
    drawBarGraph(context);

    // Draw the line graph
    for (var i = 0, l = lineGraphElementList.length; i < l; i++) {
      var currentItem = lineGraphElementList[i],
        previousItem = lineGraphElementList[i-1];

      drawLineGraphPoint(context, currentItem);
      drawLineGraphLine(context, currentItem, previousItem);
    }

    global.addEventListener('resize', resize, false);
  }

  var imgElement = container.querySelector("img");

  if (imgElement.complete) {
    // The image is already loaded!
    initializeDrawing()
  } else {
    // The image is not loaded, let's attach an event handler to it
    imgElement.addEventListener('load', initializeDrawing, false);
  }
}

var canvasElement = document.querySelector('#graph-canvas'),
    graphElement = document.querySelector('.b2b-graph-container');

if (canvasElement && graphElement) {
  drawGraph(window, graphElement, canvasElement);
}


            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console