在画布上单击画圆圈

时间:2017-11-03 13:29:58

标签: javascript css html5 canvas

您好我正在尝试创建一个用户点击canvas元素时绘制圆圈的代码。因此,当用户点击画布元素时,在画布中绘制一个圆圈。

var canvas =document.querySelector('canvas');
var c = canvas.getContext('2d');


var putLeaves = function() {
c.beginPath();
c.arc(300,300,30,0,Math.PI*2,false);
c.fillStyle ="#d57b85"
c.fill
}

canvas.addEventListner('mousedown', putLeaves)
#canvas{
position: absolute;
left: 44%;
top: 15%;
margin: 0;
border: 1px solid black;
}
<canvas id="canvas" width="300" height="200"></canvas>

1 个答案:

答案 0 :(得分:0)

您将需要使用此处的Element.getBoundingClientRect方法:https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

<script>
var canvas =document.querySelector('canvas');
var c = canvas.getContext('2d');


var putLeaves = function(e) {
  var bounds = e.target.getBoundingClientRect();
  var x = e.clientX - bounds.left;
  var y = e.clientY - bounds.top;

  c.beginPath();
  c.arc(x,y,30,0,Math.PI*2,false);
  c.fillStyle ="#d57b85"
  c.fill
}

canvas.addEventListener('mousedown', putLeaves)
</script>