首页 > 解决方案 > 在 DataTables 中绘制画布形状

问题描述

我有一个DataTable,我想canvas在一个单元格内绘制一个形状。例如,在附加的代码中,我希望在“符号”列下有一个红色三角形。下面还包括我如何绘制形状的示例。

请问我该怎么做?

<!DOCTYPE html>
<html>
<head>
    <!--jquery -->
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>

    <!-- datatables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
    <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
</head>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<table id="example" class="display" cellspacing="0" width="100%">
    <thead>
    <tr>
        <th>Team</th>
        <th>Decription</th>
        <th>Symbol</th>
    </tr>
    </thead>
</table>
<hr>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var p = {x: 150, y: 75};
var r = 50;

ctx.beginPath();
ctx.moveTo(p.x - r, p.y + r);
ctx.lineTo(p.x, p.y - r);
ctx.lineTo(p.x + r, p.y + r);
ctx.closePath();
ctx.strokeStyle = "#FF0000";
ctx.lineWidth = 10;
ctx.stroke()

var myData = [["Team A", "Red Triangle", "Drawing goes here", ]]

$(document).ready(function () {
    var table = $('#example').DataTable({
        'data': myData,
    });
});
</script>

</body>
</html>

标签: javascripthtmlcanvasdatatables

解决方案


这些数据表有​​一个渲染,你可以做一些花哨的事情。
只需将画布注入那里,然后进行绘图。

这样的事情应该做:

var myData = [ ["Team A", "Red Triangle", "Drawing goes here" ] ]

$(document).ready(function() {
  var table = $('#example').DataTable({
    'data': myData,
    'columns': [
      {"data": 0, "orderable": true},
      {"data": 1, "orderable": true },
      {
        "render": function(data, type, JsonResultRow, meta) {
          return '<canvas id="myCanvas" width="50" height="40"></canvas>';
        }
      }
    ],
  });
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  var p = {x: 35, y: 20};
  var r = 10;

  ctx.beginPath();
  ctx.moveTo(p.x - r, p.y + r);
  ctx.lineTo(p.x, p.y - r);
  ctx.lineTo(p.x + r, p.y + r);
  ctx.closePath();
  ctx.strokeStyle = "#FF0000";
  ctx.lineWidth = 5;
  ctx.stroke()
});
<!DOCTYPE html>
<html>

<head>
  <!--jquery -->
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>

  <!-- datatables -->
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
  <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
</head>

<body>

  <table id="example" class="display" cellspacing="0" width="100%">
    <thead>
      <tr>
        <th>Team</th>
        <th>Decription</th>
        <th>Symbol</th>
      </tr>
    </thead>
  </table>
  <hr>

</body>

</html>

但我个人不会真正使用画布,我只会使用图像。


推荐阅读