1

按照 w3c 学校对画布的解释,我了解创建形状...

<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var centerX = canvas.width / 2;
  var centerY = canvas.height / 2;
  var radius = 20;

  context.beginPath();
  context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  context.fillStyle = 'green';
  context.fill();
  context.lineWidth = 5;
  context.strokeStyle = '#003300';
  context.stroke();
</script>

这将在我的画布所在的位置形成一个绿色圆圈。

<canvas id="myCanvas"></canvas>

但是 - 我想将该“圆圈”应用于页面上的多个位置,而通过 ID 执行此操作将是荒谬的。

如何将上下文(如上定义)应用于多个画布?我假设使用类,这似乎是合乎逻辑的方式。

<canvas class="redDot"></canvas>
<canvas class="redDot"></canvas>
<canvas class="redDot"></canvas>

<canvas class="greenDot"></canvas>
<canvas class="greenDot"></canvas>

<canvas class="blueDot"></canvas>
<canvas class="blueDot"></canvas>
<canvas class="blueDot"></canvas>
4

1 回答 1

0

You would have to iterate through each Element to apply the changes. I.E:

var dots = document.getElementsByClassName('dots');
for (var i=0;i<dots.length;i++){
    var canvas = dots[i];
    var context = canvas.getContext('2d');
    // Draw circles here 
}

Ideally, you would only have one canvas element which you can draw multiple circles

var canvas = document.getElementById('myOneAndOnlyCanvas');
// Using CSS and layering can make background
var context = canvas.getContext('2d');

dot('red',50,50);
dot('blue',100,50);
//etc..

function dot(color,x,y){
  context.beginPath();
  context.arc(y, y, radius, 0, 2 * Math.PI, false);
  context.fillStyle = color;
  context.fill();
  context.lineWidth = 5;
  context.strokeStyle = '#003300';
  context.stroke();
}

But if that doesn't fit your use case what about using an SVG object?

Since you mentioned w3 schools: http://www.w3schools.com/svg/ But ideally check out: http://www.w3.org/Graphics/SVG/

Mind, Dom Heavy pages can seriously hurt load times. Depending on what you want to do it might be wiser just to use an image (eg. a large cluster of dots).

于 2013-04-18T16:25:11.527 回答