gpt4 book ai didi

javascript - 在 Canvas 上绘图 : mouseover and mouseclick

转载 作者:行者123 更新时间:2023-12-02 16:40:20 25 4
gpt4 key购买 nike

我添加了一个片段以使其更易于理解。

此代码片段仅在鼠标悬停时绘制,但我希望它仅在您单击并同时移动时绘制。

我尝试使用下面的代码来执行此操作,但它不起作用。

$(document).on('mouseover click','#canvas', function(event){
if(event.type == "mouseover" && event.type == "click"){
alert("e");
}
});

//开始片段

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

$("#canvas").mousemove(function(arg) {
context.fillStyle = "#1477CC";
var pos = getMousePos(canvas, arg);
context.beginPath();
context.arc(pos.x+50,pos.y,5,0,2*Math.PI);
context.fill();
});

function getMousePos(canvas, e) {
var rect = canvas.getBoundingClientRect();
return {
x: e.clientX - rect.left,
y: e.clientY - rect.top
};
}

//Clear

$("#clear").click(function() {
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0,0,380,300);
});
#canvas{
border: 1px solid black;
}

#clear:hover{
cursor: pointer;
text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<canvas id="canvas">

</canvas>

<div onclick="clear();" id="clear">
Clear
</div>

最佳答案

按照建议,您可以添加一个标志来启用绘图:

var enableDraw = false;

$("#canvas").mousedown(function(arg) {
enableDraw = true;
});

$("#canvas").mouseup(function(arg) {
enableDraw = false;
});

$("#canvas").mousemove(function(arg) {
if(enableDraw){
context.fillStyle = "#1477CC";
var pos = getMousePos(canvas, arg);
context.beginPath();
context.arc(pos.x+50,pos.y,5,0,2*Math.PI);
context.fill();
}
});

FIDDLE

关于javascript - 在 Canvas 上绘图 : mouseover and mouseclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27569431/

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