我在主画布上画了一些彩色线条。有3种颜色可供选择:红色,绿色,蓝色。为了进一步的使用,我有3个小画布(称为#canvasR #canvasG和#canvasB),我根据其颜色绘制每条线,例如。所有(也是唯一的)#canvasR中的红色。除了一个很大的神秘之处外,一切都很完美:当我在主画布上画出第一条蓝线(onmousemove> onmouseup)时,第二条蓝线出现在#canvasB中...一切都是正确的。但是当我想在其他地方绘制第二条蓝线时(第二个onmousemove> onmouseup序列)主画布中的所有内容都可以,但#canvasB中没有:不需要的新蓝线连接第一个和新的蓝线,就像如果第一个onmouseup被忽略了...截图: http://e-vdn.com/4canvas.png
canvas.mousemove(function(e) {
cursorX = (e.pageX - this.offsetLeft);
cursorY = (e.pageY - this.offsetTop);
drawLine();
});
function drawLine() {
// in main canvas:
context.lineTo(cursorX, cursorY);
context.strokeStyle = color;
context.lineWidth = width_brush;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = width_brush*1.5;
context.shadowColor = color;
context.stroke();
// in small canvas:
if (color=='#f00') { ctx = ctxR; }
if (color=='#9f0') { ctx = ctxV; }
if (color=='#00f') { ctx = ctxB; }
ctx.lineTo( (cursorX/4), (cursorY/4) );
ctx.strokeStyle = color;
ctx.lineWidth = width_brush;
ctx.stroke();
}
答案 0 :(得分:0)
您必须为每个新笔划执行context.beginPath,否则该上下文中的所有上一行将与您当前的笔划一起重绘。
因此,例如,假设您执行(1)红色笔划,然后执行(2)蓝色笔划。如果没有context.beginPath,您的红色笔划将使用当前的蓝色笔重新绘制。
这是您未经测试的代码重构:
var lastX,lastY;
var lastRedX,lastRedY,lastGreenX,lastGreenY,lastBlueX,lastBlueY;
// in main canvas:
if(lastX){
context.beginPath();
context.moveTo(lastX,lastY);
context.lineTo(cursorX, cursorY);
context.strokeStyle = color;
context.lineWidth = width_brush;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = width_brush*1.5;
context.shadowColor = color;
context.stroke();
}
lastX=cursorX;
lastY=cursorY;
// in small red canvas:
if (color=='#f00')
if(lastRedX){
addLine(ctxR,lastRedX,lastRedY,cursorX,cursorY);
}
lastRedX=cursorX;
lastRedY=cursorY;
}
// in small V canvas:
if (color=='#9f0')
if(lastGreenX){
addLine(ctxV,lastGreenX,lastGreenY,cursorX,cursorY);
}
lastGreenX=cursorX;
lastGreenY=cursorY;
}
// in small Blue canvas:
if (color=='#00f')
if(lastBlueX){
addLine(ctxB,lastBlueX,lastBlueY,cursorX,cursorY);
}
lastBlueX=cursorX;
lastBlueY=cursorY;
}
function addLine(ctx,lastX,lastY,cursorX,cursorY){
ctx.beginPath();
ctx.moveTo( lastX,lastY );
ctx.lineTo( (cursorX/4), (cursorY/4) );
ctx.strokeStyle = color;
ctx.lineWidth = width_brush;
ctx.stroke();
}