2013-05-12 60 views
1

我有一个分布在div上的画布,我试图在位置0,0上画一个矩形,并在需要时将它移动到另一个位置x,y。我需要的x,y位置正在完美地返回,我正在使用clearRect(0, 0, canvas.width, canvas.height)方法来清除画布,当我需要移动并再次使用fillRect(x, y, width, height)重绘这些特定位置时。然而,虽然x,y的位置是好的,fillRect(..)被调用(我在铬中调试),矩形只是被删除和绘制时,我在位置0,0重绘它,否则它只是删除。起初我认为它正在被绘制,但也许div和canvas的分层正在丢失,但我将它放置在其他地方,并且这不是问题。在不同的x,y位置画布重绘一个矩形

这是我可能有人可能会在我的代码中看到错误的代码!由于

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是当前选择的坐标。

任何想法这里有什么不对?

+0

作者:“X,Y是当前选择的坐标”,你指的是光标坐标吗? X和Y是如何确定的以及与什么元素有关? – Nikki 2013-05-13 09:45:18

+0

居然是这个问题@Nikki! x和y坐标不能正确返回,因为它们是根据视口而不是内容可编辑div进行计算的。请看这个问题,也许你可以回答:http://stackoverflow.com/questions/16524842/get-x-y-position-of-selection-relative-to-a-contenteditable-div – Bernice 2013-05-13 16:28:49

回答

0

你为什么不重新因子

function rePaintCursor(x, y, connectionId, color) { 
    var canvas = document.getElementById(connectionId); 
    var context = canvas.getContext('2d'); 
    context.clearRect(0, 0, canvas.width, canvas.height); 
    context.fillStyle = color; 
    context.fillRect(x, y, 0.75, 5); 
} 

我的猜测是,如果X和Y是正确的,执行顺序可能是你的方式。

相关问题