Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptD3.js line.context() method

D3.js line.context() method

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;">
           neveropen
    </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;">
         neveropen
     </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:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments