簡體   English   中英

創建外部 JavaScript 文件並在 HTML5 畫布上調用它

[英]Create external JavaScript file and call it on HTML5 canvas

我正在使用 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;
  }
}

在運行代碼之前,您需要等待畫布等項目加載到 DOM 中。 您可以將其保留在<head>標記中並將代碼包裝在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>

您的問題是您試圖在<canvas>內附加一個<canvas> ,這是毫無意義的。 這一行:

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

查找 ID 為“canvas”的元素並在其中添加<canvas> 但是在您的 HTML 中,該元素是一個畫布:

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

如果您只是將其更改為<div> ,例如:

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

你的代碼會起作用。 這是一個向您展示的工作小提琴(我所做的唯一一件事就是上述更改): https : //jsfiddle.net/vcg1pk9v/1/

另外,請記住 Spencer 的回答:操作該 div 的代碼必須創建該 div之后出現(在 JSFiddle 中,代碼將自動運行)。 一個好的做法是在關閉<body>之前放置它(或調用它,如果是外部的)。 話雖如此,您的問題實際上有兩個問題; 斯賓塞處理了其中一個,我處理了另一個。

嘿,在你定義你的畫布之后調用它。

使用<script src="script path here"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM