【发布时间】:2015-08-06 14:22:25
【问题描述】:
我允许用户在图像上绘制矩形。同时,用户应该能够在任何时间点调整或移动任何矩形。 在一些帮助下,我已经能够绘制矩形,但我无法调整大小和移动其中的一部分。 正在绘制的矩形不会相互重叠,并且在调整大小和移动时也必须对其进行验证。 我正在使用 javascript 和 jquery。 这是我到目前为止所做的demo:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var startX;
var startY;
var isDown = false;
ctx.strokeStyle = "lightgray";
ctx.lineWidth = 3;
function handleMouseDown(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mousedown stuff here
startX = mouseX;
startY = mouseY;
isDown = true;
}
function handleMouseUp(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
$("#uplog").html("Up: " + mouseX + " / " + mouseY);
// Put your mouseup stuff here
isDown = false;
}
function handleMouseMove(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mousemove stuff here
if (!isDown) {
return;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawRectangle(mouseX, mouseY);
}
function drawRectangle(mouseX, mouseY) {
var width = mouseX - startX;
var height = mouseY - startY;
ctx.beginPath();
ctx.rect(startX, startY, width, height);
ctx.stroke();
}
$("#canvas").mousedown(function (e) {
handleMouseDown(e);
});
$("#canvas").mousemove(function (e) {
handleMouseMove(e);
});
$("#canvas").mouseup(function (e) {
handleMouseUp(e);
});
因为我的时间不多了,我无法弄清楚如何做到这一点。
【问题讨论】:
-
你不能只在画布上绘制对象如果你想移动它们。您需要创建形状对象的实例并管理它们(根据需要进行命中测试和渲染)。它不是很复杂,但需要比目前更多的代码。
-
您有什么建议或示例可以分享,以便我在这些方面工作吗?
-
我无法将它与我的代码集成。不知道如何使用它。
标签: javascript jquery html canvas