【发布时间】:2013-05-12 14:13:54
【问题描述】:
我有一个覆盖在 div 上的画布,我试图在加载时在位置 0、0 处绘制一个矩形,并在需要时将其移动到另一个位置 x、y。我需要的 x、y 位置正在完美返回,当我需要移动时使用clearRect(0, 0, canvas.width, canvas.height) 方法清除画布并再次使用fillRect(x, y, width, height) 在这些特定位置重绘。但是,尽管 x、y 位置很好并且正在调用 fillRect(..)(我在 chrome 中调试),但只有当我在位置 0、0 处重新绘制它时,矩形才会被移除和绘制。否则它只会被移除。起初我以为它正在绘制,但可能 div 和画布的分层丢失了,但我将它放置在其他地方,不,这不是问题。
这是我的代码,也许有人会在我的代码中看到一些错误!谢谢
function removeCursor(connectionId) {
var canvas = document.getElementById(connectionId);
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function paintCursor(x, y, connectionId, color) {
var canvas = document.getElementById(connectionId);
var context = canvas.getContext('2d');
context.fillStyle = color;
context.fillRect(x, y, 0.75, 5);
}
// the canvas is created on someone connecting to a specific page
if (someoneConnected) {
var canvas = document.createElement("canvas");
canvas.id = connectionId;
canvas.className = 'canvases';
canvas.style.zIndex = zindex;
zindex++;
var parentDiv = document.getElementById("editor-section");
parentDiv.appendChild(canvas);
paintCursor(0, 0, connectionId, color);
} else { // someone disconnected
var canvas = document.getElementById(connectionId);
canvas.parentNode.removeChild(canvas);
}
我在用户事件(例如按键和单击)上调用方法removeCursor(connectionId) 和paintCursor(x, y, connectionId, color)。 X, Y 是当前选择的坐标。
有什么想法吗?
【问题讨论】:
-
by: "X, Y 是当前选择的坐标",你指的是光标坐标吗? X 和 Y 如何确定以及与什么元素相关?
-
实际上这是@Nikki 的问题! x 和 y 坐标没有正确返回,因为它们是根据视口而不是内容可编辑 div 计算的。请看这个问题也许你可以回答:stackoverflow.com/questions/16524842/…
标签: javascript jquery html css canvas