如何在HMTL5画布上绘制矩形时清除轨迹
How to clear trails when drawing rectangles on an HMTL5 canvas
我目前正在开发一个应用程序,在画布上绘制一个矩形。我可以完美地画出矩形,但当我试图改变鼠标的移动以使矩形变小时,会留下一些痕迹。当我缩小矩形的大小时,如何清除这些痕迹?下面是我使用的JavaScript代码。提前谢谢。
function drawSquare() {
// creating a square
var w = lastX - startX;
var h = lastY - startY;
var offsetX = (w < 0) ? w : 0;
var offsetY = (h < 0) ? h : 0;
var width = Math.abs(w);
var height = Math.abs(h);
context.beginPath();
context.rect(startX + offsetX, startY + offsetY, width, height);
context.fillStyle = "gold";
context.fill();
context.lineWidth = 1;
context.strokeStyle = 'red';
context.stroke();
canvas.style.cursor = "default";
}
function getMousePos(canvas, e) {
var rect = canvas.getBoundingClientRect();
return {
x: e.pageX - canvas.offsetLeft,
y: e.pageY - canvas.offsetTop,
};
}
function handleMouseDown(e) {
// get mouse coordinates
mouseX = parseInt(e.pageX - offsetX);
mouseY = parseInt(e.pageY - offsetY);
// set the starting drag position
lastX = mouseX;
lastY = mouseY;
isDown = true;
if (isChecBoxClicked == true) {
mouseIsDown = 1;
startX = lastX;
startY = lastY;
var pos = getMousePos(canvas, e);
startX = lastX = pos.x;
startY = lastY = pos.y;
drawSquare();
}
else {
canvas.style.cursor = "default";
}
}
function handleMouseUp(e) {
// clear the dragging flag
isDown = false;
canvas.style.cursor = "default";
// get mouse coordinates
mouseX = parseInt(e.pageX - offsetX);
mouseY = parseInt(e.pageY - offsetY);
// set the starting drag position
lastX = mouseX;
lastY = mouseY;
if (isChecBoxClicked == true)
{
canvas.style.cursor = "crosshair";
if (mouseIsDown !== 0) {
mouseIsDown = 0;
var pos = getMousePos(canvas, e);
lastX = pos.x;
lastY = pos.y;
drawSquare();
}
}
}
function handleMouseMove(e) {
// if we're not dragging, exit
if (!isDown) {
return;
}
//if (defaultval == 1) {
// return;
//}
if (isChecBoxClicked == true) {
canvas.style.cursor = "crosshair";
if (mouseIsDown !== 0) {
var pos = getMousePos(canvas, e);
lastX = pos.x;
lastY = pos.y;
drawSquare();
}
}
}
画布不会自行清除。至少不是像您正在使用的那样的二维上下文。如果继续在上面绘制,则新图形将放置在旧图形的顶部。你需要明确地清除它:
context.clearRect(0, 0, canvas.width, canvas.height);
您可能需要清除画布。如果只绘制正方形,则必须在drawSquare
函数中执行此操作。如果你要画多个东西,你必须在一个更高的函数中重新绘制多个东西。
为了清除整个画布,您可以使用以下代码:
context.clearRect ( 0 , 0 , canvas.width, canvas.height );
还有很多画布库可以为您管理这一点,并优化重新绘制的区域(它们可能只清除画布的一部分,因此重新绘制的像素较少)
相关文章:
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- 单击jquery清除输入值
- Javascript时间轨迹
- 如何在Microsoft VirtualEarth 6.3中使用纯javascript清除整个形状层
- 清除以前的$_GET值或不获取仅隐藏字段的值
- Javascript清除缓存以清除基本身份验证凭据
- 清除启动日期选取器值
- 在 SlickGrid 中编辑后,根据不同列中的另一个单元格清除单元格
- php页面,该页面在清除值后接受输入
- 清除数据并将旧值附加到文本框中
- 使用javascript清除Asp.NET FreeTextBox(RTF文本框)
- 如何使Visual Studio自动清除Javascript控制台
- 鼠标悬停时播放随机轨迹
- 使用javascript或html本身清除文本字段
- 清除函数中if语句内部不起作用的间隔
- 我应该/如何清除mousemove JQuery事件侦听器
- 从定位目标中的元素中清除类
- 使用查询字符串方法清除浏览器缓存
- 如何在使用AngularJS更改下拉值时清除表单中的数据
- 如何在HMTL5画布上绘制矩形时清除轨迹