HTML5画布-绘制

时间:2018-09-09 19:54:17

标签: html5 html5-canvas

圆圈示例如下

这是我的JavaScript代码。

<canvas id="testCanvas" style="border:1px solid #000000;"></canvas>

1 个答案:

答案 0 :(得分:1)

假设您的randomColor是正确的,则只需要:

  • 从canvas.onclick中删除context.clearRect
  • context.beginPath移动到canvas.onclick

这是一个工作样本

var canvas = document.getElementById("testCanvas");
var context = canvas.getContext("2d");

function randomColor() {
  colorArray = ["red", "blue", "green", "lime", "orange", "cyan"]
  return colorArray[Math.floor(Math.random() * colorArray.length)];
}


// click event handler
canvas.onclick = function(e) {
  x = e.clientX - e.target.offsetLeft;
  y = e.clientY - e.target.offsetTop;

  context.beginPath();
  context.fillStyle = randomColor();
  context.arc(x, y, 25, 0, 2 * Math.PI, true);
  context.fill();
}
<canvas id="testCanvas" style="border:1px solid #000000;"></canvas>