我使用React在客户端鼠标坐标的画布上绘图。
但是,我也尝试使用客户端的鼠标坐标清除现有画布。我怎么能这样做?基本上画布只会在鼠标悬停区域中清除。
最后有没有办法使用context
将样式属性添加到此路径?
答案 0 :(得分:0)
我想到了一些可以帮助您的东西。
<body id="paper" onload="init()">
<canvas id="canvas" width="200" height="200" style="border: 1px solid #000" onmousedown="deleting=true" onmouseup="deleting=false"></canvas>
</body>
<script type="text/javascript">
var mouseX = 0, mouseY = 0;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var body = document.getElementById("paper");
var deleting = false;
function init() {
window.addEventListener("mousemove", function(e) {
mouseX = e.pageX - canvas.offsetLeft;
mouseY = e.pageY - canvas.offsetTop; //this updates the mouse coordinates
});
if (typeof mousemove != "undefined") {
window.addEventListener("mousemove", mousemove);
}
}
function draw() {
ctx.fillStyle = "#F00";
ctx.fillRect(0, 0, canvas.width, canvas.height); //red rect filling the canvas
}
function update() {
if (deleting) {
ctx.clearRect(mouseX, mouseY, 10, 10); //10 is our "brush size", you can change that.
}
}
update();
setInterval(update, 10); //JavaScript must keep checking if you're deleting anything. You can decrease the interval for more frequent updating.
draw();
</script>
如果您正在开发有关绘图的应用程序,这应该使您了解如何制作它。
ctx.fillRect(mouseX, mouseY, 10, 10);
是绘图的工作方式。