所以我想做一條線跟隨鼠標,並點擊繪製該線,我需要這個繪製多邊形。我的想法是每次鼠標移動時畫一條線,但隨後會弄亂很多線條,所以我決定在用白色線條移動鼠標並清理之後,畫出過去的線條,這樣只會有一條線條出現從最後一次點擊到當前鼠標位置。 My jsFiddle for this.,但它不工作的方式,我想是的,我在點擊繪製多邊形,但沒有線跟隨鼠標,所以我不能看到我正在繪製的線。我不明白哪裏錯了?也許有一些現成的解決方案,我沒有找到?我的代碼:html canvas一條線跟隨鼠標
var polygonX = [];
var polygonY = [];
var lineReady = 0;
var whileLineX;
var whiteLineY;
$("#body").bind('mousemove', function (ev) {
if (lineReady >= 2) {
var context;
//clear old lines
if (whiteLineX !== null && whiteLineY !== null) {
context = $("#canvas")[0].getContext('2d');
context.moveTo(polygonX[lineReady - 1], polygonY[lineReady - 1]);
context.lineTo(whiteLineX, whiteLineY);
context.strokeStyle = '#ffffff';
context.stroke();
}
//draw a new line
context = $("#canvas")[0].getContext('2d');
var offset = $('#body').offset();
var x = ev.clientX - offset.left;
var y = ev.clientY - offset.top;
context.beginPath();
context.moveTo(polygonX[lineReady - 1], polygonY[lineReady - 1]);
context.strokeStyle = '#000000';
context.lineTo(x, y);
context.stroke();
whileLineX = x;
whiteLineY = y;
}
});
$("#body").bind('click', function (ev) {
var offset = $('#body').offset();
var x = ev.clientX - offset.left;
var y = ev.clientY - offset.top;
polygonX
.push(x);
polygonY.push(y);
lineReady++;
if (lineReady >= 2) {
var context = $("#canvas")[0].getContext('2d');
context.beginPath();
context.moveTo(polygonX[lineReady - 2], polygonY[lineReady - 2]);
context.lineTo(polygonX[lineReady - 1], polygonY[lineReady - 1]);
context.stroke();
}
});`
無論何時鼠標移動到上方,使用z-index使用兩個畫布, ,然後清除整個畫布並從源繪製一條線到該鼠標位置。一旦鼠標被釋放,從畫布下面的源代碼到目的地的行再次擦除上面的那個 – Shadow