I have 2 canvas and want to be able to draw on either one of those canvas on button click. I can draw on my canvas but cant draw on other canvas when clicking the other button. Checking console.log, it seems the other canvas is not responding to mousedown when toggled. I'm trying to prevent being able to draw on both canvas at the same time.
Html
<button class="btn btn-primary" onclick="switchCanvas('other-canvas')">Switch Other</button>
<button class="btn btn-primary" onclick="switchCanvas('my-canvas')">Switch Mine</button>
<div class="row justify-content-center">
<canvas id="other-canvas" width="500" height="250" style="border: 2px solid grey;"></canvas>
<canvas id="my-canvas" width="500" height="250" style="border: 2px solid grey;"></canvas>
</div>
Script
let canvas = document.getElementById('my-canvas');
ctx = canvas.getContext('2d');
let color ='black'
var width = 2;
ctx.lineWidth = width;
ctx.lineCap = 'round';
ctx.lineJoin = 'round'
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
window.switchCanvas = function(id){
canvas = document.getElementById(id);
ctx = canvas.getContext('2d');
}
var mousedown = false;
canvas.onmousedown = function(e) {
var pos = fixPosition(e, canvas);
mousedown = true;
data = {
pos:pos,
width:width,
color:color
}
console.log(data)
mouseDown(data)
return false;
};
function mouseDown(data){
ctx.lineWidth = data.width;
ctx.strokeStyle = data.color;
ctx.beginPath();
ctx.moveTo(data.pos.x, data.pos.y);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…