Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

javascript - Toggle drawing between 2 html canvas

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...