gpt4 book ai didi

javascript - 单击 Canvas 上绘制圆圈

转载 作者:行者123 更新时间:2023-11-28 04:01:10 25 4
gpt4 key购买 nike

您好,我正在尝试创建一个代码,当用户单击 Canvas 元素时绘制一个圆圈。因此,当用户单击 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>

最佳答案

您将需要使用此处找到的 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>

关于javascript - 单击 Canvas 上绘制圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47096964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com