使用相同的鼠标输出(同时)绘制多个HTML CANVAS

时间:2019-06-17 22:41:21

标签: javascript html canvas

也许这是一个愚蠢的问题,但我不知道发生了什么。我正在研究使用HTML CANVAS进行数字绘图,并且希望在同一鼠标移动输出的情况下(同时)在多个CANVAS中进行绘图。我绘制了一个函数来处理每个CANVAS的上下文(ctx)(ctx,xpos,ypos,bool)。但是,每次我尝试使用它时,它只会吸引其中之一。 我在这里举了一个例子 https://jsfiddle.net/rboyart/Lgzwry02/1/ (如果单击并在空白处移动,则应同时绘制两个CANVAS)

    <style>
    html, body {height: 100%}
    .full-height {height: 100%}

    canvas {background-color:#ddd; z-index:-1; float: left; margin-right:10px}
    .objectBox {z-index: 0; position: relative; top:0; left:0 }
    </style>

    <canvas id="canvas1" width="200" height="200" ></canvas>
    <canvas id="canvas2" width="200" height="200" ></canvas>
    <div id="objectBox" class="full-height" style="width:100%; height:100%; background-color:transparent;">
            </div>

<script type="text/javascript"> var canvas1 = document.getElementById('canvas1'); var ctxPaint = canvas1.getContext('2d'); var canvas2 = document.getElementById('canvas2'); var ctxPaint2 = canvas2.getContext('2d'); var isDrawing, lastPoint; function drawing(ctx, xpos, ypos, bool) { if(!bool){ lastPoint = { x: xpos, y: ypos } } if(bool) { ctx.lineJoin = "round"; ctx.lineCap = "butt"; ctx.strokeStyle = "#000000"; ctx.globalAlpha = "1"; ctx.globalCompositeOperation = "source-over"; if(ctx.lineWidth >= 5) { ctx.lineWidth -= 0.1; } var currentPoint = { x: xpos, y: ypos }; ctx.beginPath(); ctx.moveTo(lastPoint.x, lastPoint.y); ctx.lineTo(currentPoint.x, currentPoint.y); ctx.closePath(); ctx.stroke(); lastPoint = currentPoint; } } /*END FUNCTION DRAWING */ function findObjectCoords(mouseEvent) { var obj = document.getElementById("objectBox"); var widthOBJ = obj.clientWidth; var heightOBJ = obj.clientHeight; var obj_left = 0; var obj_top = 0; var xpos; var ypos; while (obj.offsetParent) { obj_left += obj.offsetLeft; obj_top += obj.offsetTop; obj = obj.offsetParent; } obj.onmousedown = function(e) { isDrawing = true; }; obj.onmouseup = function() { isDrawing = false; }; if (mouseEvent) { xpos = mouseEvent.pageX; ypos = mouseEvent.pageY; } else { xpos = window.event.x + document.body.scrollLeft - 2; ypos = window.event.y + document.body.scrollTop - 2; } xpos -= obj_left; ypos -= obj_top; var numX = map_range(xpos, 0, widthOBJ, 0, 200); var numY = map_range(ypos,0, heightOBJ, 0, 200);  drawing(ctxPaint, parseInt(numX), parseInt(numY), isDrawing); drawing(ctxPaint2, parseInt(numX), parseInt(numY), isDrawing); } document.getElementById("objectBox").onmousemove = findObjectCoords; function map_range(value, low1, high1, low2, high2) { return low2 + (high2 - low2) * (value - low1) / (high1 - low1); } </script>

1 个答案:

答案 0 :(得分:1)

这是因为您的lastPoint变量用于两个画布。第一次调用drawing时,lastpoint被覆盖。因此,第二次调用drawing时,您的lastPoint已经是当前点=>没有绘制点。

要解决此问题,您可以使用2个单独的lastPoint变量,或者仅在第二次调用lastPoint时更新drawing,就像我在这里所做的那样:https://jsfiddle.net/ay45sx19/