如何解决在 2 个 html 画布之间切换绘图
我有 2 个画布,希望能够在单击按钮时在其中任一画布上进行绘制。我可以在我的画布上绘图,但单击其他按钮时无法在其他画布上绘图。检查 console.log,似乎另一个画布在切换时没有响应 mousedown。我试图防止能够同时在两个画布上绘制。
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>
脚本
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,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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。