Open In App
Related Articles

D3.js line.context() method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The d3.line.context() method lets you render the line in a canvas element’s context. The line will be rendered in the current context when the line generator is invoked. We can set the context of our line on our own using this method like color, stroke, fill, etc. The default value is null.

Syntax:

d3.line.context(_context);

Parameters:

  • _context: context set by the user.

Return Value: This method returns the current context.

Example 1: In this example, change color, stroke using this method.

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
  <title>d3.line.defined()</title>
</head>
<script src=
</script>
  
<body>
    <h1 style="text-align: center; 
        color: green;">
           GeeksforGeeks
    </h1>
  <center>
    <canvas id="gfg" width="200" height="200">
      </canvas>
</center>
  <script>
    var points = [
      {x: 0, y: 0},  
      {x: 1, y: 3},
      {x: 2, y: 15},
      {x: 3, y: 8},
      {x: 4, y: 11},
      {x: 5, y: 15},
      {x: 6, y: 20},
      {x: 7, y: 25}];
    var xp = d3.scaleLinear().domain([0, 7]).range([25, 200]);
    var yp = d3.scaleLinear().domain([0, 25]).range([175, 25]);
    var cont = d3.select("#gfg").node().getContext("2d");
    var line = d3.line()
      .x(d => xp(d.x))
      .y(d => yp(d.y))
      .context(cont);
  
    line(points);
  
    cont.strokeStyle = "green";
    cont.stroke();
</script>
</body>
</html>

                    

Output:

Example 2: In this example, change color, fill using this method.

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
  <title>d3.line.defined()</title>
</head>
<script src=
 </script>
  
<body>
    <h1 style="text-align: center; color: green;">
         GeeksforGeeks
     </h1>
  <center>
    <canvas id="gfg" width="200" height="200"></canvas>
</center>
  <script>
    var points = [
      {x: 0, y: 0},  
      {x: 1, y: 3},
      {x: 2, y: 15},
      {x: 3, y: 8},
      {x: 4, y: 11},
      {x: 5, y: 15},
      {x: 6, y: 20},
      {x: 7, y: 25}];
    var xp = d3.scaleLinear().domain([0, 7]).range([25, 200]);
    var yp = d3.scaleLinear().domain([0, 25]).range([175, 25]);
    var cont = d3.select("#gfg").node().getContext("2d");
    var line = d3.line()
      .x(d => xp(d.x))
      .y(d => yp(d.y))
      .context(cont);
  
    line(points);
  
    cont.strokeStyle = "green";
    cont.fill();
</script>
</body>
</html>

                    

Output:



Last Updated : 17 Aug, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads