【问题标题】:Create external JavaScript file and call it on HTML5 canvas创建外部 JavaScript 文件并在 HTML5 画布上调用它
【发布时间】:2016-10-02 23:37:00
【问题描述】:

我正在使用 D3.js 库在简单的 HTML5 画布中创建示例动画。

但我不会在 HTML 代码中使用 <script>。我需要创建一个文件并将其放在那里。那么,如何在 HTML 代码中调用它呢?

这是我的 html 文件:

<!DOCTYPE html>
<html>
    
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/estilo.css">
    <script src="https://d3js.org/d3.v3.min.js"></script>
    <script src="js/delaunayanimation.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
    <section>
        <canvas id="canvas">
            //how to call javascript here?
        </canvas>
    </section>
</body>
</html>

这是我作为外部创建的脚本(它的名称是 delaunayanimation.js):

var width = 960,
    height = 500,
    τ = 2 * Math.PI,
    gravity = .05;

var sample = poissonDiscSampler(width, height, 30),
    nodes = [{x: 0, y: 0}],
    s;

while (s = sample()) nodes.push(s);

var force = d3.layout.force()
    .size([width, height])
    .nodes(nodes.slice())
    .gravity(0)
    .charge(function(d, i) { return i ? -30 : -3000; })
    .on("tick", ticked)
    .start();

var voronoi = d3.geom.voronoi()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });

var root = nodes.shift();

root.fixed = true;

var links = voronoi.links(nodes);

var canvas = d3.select("#canvas").append("canvas")
    .attr("width", width)
    .attr("height", height)
    .on("ontouchstart" in document ? "touchmove" : "mousemove", moved);

var context = canvas.node().getContext("2d");
    
function moved() {
  var p1 = d3.mouse(this);
  root.px = p1[0];
  root.py = p1[1];
  force.resume();
}

function ticked() {
  force.resume();

  for (var i = 0, n = nodes.length; i < n; ++i) {
    var node = nodes[i];
    node.y += (node.cy - node.y) * gravity;
    node.x += (node.cx - node.x) * gravity;
  }

  context.clearRect(0, 0, width, height);

  context.beginPath();
  for (var i = 0, n = links.length; i < n; ++i) {
    var link = links[i];
    context.moveTo(link.source.x, link.source.y);
    context.lineTo(link.target.x, link.target.y);
  }
  context.lineWidth = 1;
  context.strokeStyle = "#bbb";
  context.stroke();

  context.beginPath();
  for (var i = 0, n = nodes.length; i < n; ++i) {
    var node = nodes[i];
    context.moveTo(node.x, node.y);
    context.arc(node.x, node.y, 2, 0, τ);
  }
  context.lineWidth = 3;
  context.strokeStyle = "#fff";
  context.stroke();
  context.fillStyle = "#000";
  context.fill();
}

// Based on https://www.jasondavies.com/poisson-disc/
function poissonDiscSampler(width, height, radius) {
  var k = 30, // maximum number of samples before rejection
      radius2 = radius * radius,
      R = 3 * radius2,
      cellSize = radius * Math.SQRT1_2,
      gridWidth = Math.ceil(width / cellSize),
      gridHeight = Math.ceil(height / cellSize),
      grid = new Array(gridWidth * gridHeight),
      queue = [],
      queueSize = 0,
      sampleSize = 0;

  return function() {
    if (!sampleSize) return sample(Math.random() * width, Math.random() * height);

    // Pick a random existing sample and remove it from the queue.
    while (queueSize) {
      var i = Math.random() * queueSize | 0,
          s = queue[i];

      // Make a new candidate between [radius, 2 * radius] from the existing sample.
      for (var j = 0; j < k; ++j) {
        var a = 2 * Math.PI * Math.random(),
            r = Math.sqrt(Math.random() * R + radius2),
            x = s.x + r * Math.cos(a),
            y = s.y + r * Math.sin(a);

        // Reject candidates that are outside the allowed extent,
        // or closer than 2 * radius to any existing sample.
        if (0 <= x && x < width && 0 <= y && y < height && far(x, y)) return sample(x, y);
      }

      queue[i] = queue[--queueSize];
      queue.length = queueSize;
    }
  };

  function far(x, y) {
    var i = x / cellSize | 0,
        j = y / cellSize | 0,
        i0 = Math.max(i - 2, 0),
        j0 = Math.max(j - 2, 0),
        i1 = Math.min(i + 3, gridWidth),
        j1 = Math.min(j + 3, gridHeight);

    for (j = j0; j < j1; ++j) {
      var o = j * gridWidth;
      for (i = i0; i < i1; ++i) {
        if (s = grid[o + i]) {
          var s,
              dx = s.x - x,
              dy = s.y - y;
          if (dx * dx + dy * dy < radius2) return false;
        }
      }
    }

    return true;
  }

  function sample(x, y) {
    var s = {x: x, y: y, cx: x, cy: y};
    queue.push(s);
    grid[gridWidth * (y / cellSize | 0) + (x / cellSize | 0)] = s;
    ++sampleSize;
    ++queueSize;
    return s;
  }
}

【问题讨论】:

  • @Kaiido 我需要它在画布内渲染动画

标签: javascript jquery html canvas d3.js


【解决方案1】:

在运行代码之前,您需要等待画布等项目加载到 DOM 中。您可以将其保留在 &lt;head&gt; 标记中并将代码包装在 document.ready 中,也可以将其移动到正文的底部,如下所示:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/estilo.css">
    <script src="https://d3js.org/d3.v3.min.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
    <section>
        <canvas id="canvas">
            //how to call javascript here?
        </canvas>
    </section>
    <script src="js/delaunayanimation.js"></script>
</body>
</html>

【讨论】:

  • 不起作用。我不应该在画布内调用函数吗?
  • @coreid 不,画布中的 HTML 仅用于在浏览器不支持时显示后备消息。您需要在定义画布后调用它,只要调用该代码时,画布元素存在即可。如果它不起作用,请确保您的代码正在运行并且 JS 正在加载,并检查控制台是否有错误。
  • js 代码正在加载,但如果我将整个代码放在 html 中它可以工作,但不会作为外部 js 文件呈现。
  • @coreid 如果它是外部的或直接输入的 JavaScript,它的工作方式完全相同。他们唯一的时间是如果 JS 代码没有加载,因为它没有正确链接。
【解决方案2】:

您的问题是您试图在&lt;canvas&gt; 中附加&lt;canvas&gt;,这是没有意义的。这一行:

var canvas = d3.select("#canvas").append("canvas")

查找 ID 为“canvas”的元素,并在其中添加 &lt;canvas&gt;。但在您的 HTML 中,该元素是一个画布:

<section>
    <canvas id="canvas">
    </canvas>
</section>

如果您只是将其更改为&lt;div&gt;,例如:

<section>
    <div id="canvas">
    </div>
</section>

您的代码将起作用。这是一个工作小提琴向您展示(我唯一做的就是上面提到的更改):https://jsfiddle.net/vcg1pk9v/1/

另外,请记住 Spencer 的回答:操作该 div 的代码必须在创建该 div 之后出现(在 JSFiddle 中,代码将自动运行之后)。一个好的做法是在关闭&lt;body&gt; 之前放置它(或调用它,如果是外部的)。话虽如此,您的问题实际上有两个问题; Spencer 处理其中一个,我处理另一个。

【讨论】:

  • 谢谢,它工作正常。而不是&lt;canvas&gt; 元素,我改为&lt;div&gt; 并在此声明之后调用外部文件,但在&lt;/body&gt; 之前。
【解决方案3】:

嘿,在你定义了你的画布之后调用它。

使用&lt;script src="script path here"&gt;&lt;/script&gt;

【讨论】:

  • 剩下的在哪里?
  • 用于在页脚中加载
猜你喜欢
  • 1970-01-01
  • 2019-04-13
  • 1970-01-01
  • 2017-12-18
  • 2014-07-18
  • 2016-08-16
  • 2016-11-23
  • 2012-05-26
  • 1970-01-01
相关资源
最近更新 更多