【发布时间】:2021-10-26 02:01:21
【问题描述】:
如何加载多个画布并在其上启用绘图。目前,它在我的页面上显示了两个画布,但我只能在一个画布上绘制。
我在数据库中有两条记录。 foreach 下面的循环制作了两个画布,但我只能在一个画布上绘制,而不能在两个画布上绘制。我应该能够在两个画布上画画,这就是我想要的东西。我正在寻找有关我应该如何做的任何帮助或任何提示,以便我可以在动态生成的所有画布上绘图。
<body onload="init()">
<canvas id="can_{{$draw->id}}" width="1200" height="400"
style="position:absolute;top:10%;left:10%;border:2px solid;">
</canvas>
</body>
下面是允许用户在画布图像上绘制的js代码
<script type="text/javascript">
var canvas, ctx, flag = false,
prevX = 0,
currX = 0,
prevY = 0,
currY = 0,
dot_flag = false;
var x = "red",
y = 2;
function init() {
for(let i=1;i<3;i++){
canvas = document.getElementById('can_'+i);
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
//
canvas.addEventListener("mousemove", function (e){
findxy('move', e)
}, false);
canvas.addEventListener("mousedown", function (e) {
findxy('down', e)
}, false);
canvas.addEventListener("mouseup", function (e) {
findxy('up', e)
}, false);
canvas.addEventListener("mouseout", function (e) {
findxy('out', e)
}, false);
}//end of for
}
function draw() {
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
}
function findxy(res, e) {
if (res == 'down') {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.getBoundingClientRect().left;
currY = e.clientY - canvas.getBoundingClientRect().top;
flag = true;
dot_flag = true;
if (dot_flag) {
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(currX, currY, 2, 2);
ctx.closePath();
dot_flag = false;
}
}
if (res == 'up' || res == "out") {
flag = false;
}
if (res == 'move') {
if (flag) {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.getBoundingClientRect().left;
currY = e.clientY -canvas.getBoundingClientRect().top;
draw();
}
}
}
</script>
【问题讨论】:
-
你在后端注入的那些画布的 ID 是什么
-
{{$draw->id}} 在循环中给出 id 1 和 2
-
可能是因为您也只有一个正在绘制的上下文。
ctx = canvas.getContext("2d");我认为这会覆盖一个,因为您试图将一个变量分配给两个画布。也许分配一个 ctx1 和 ctx2 看看是否可以。 -
你的意思是 ctx1 = canvas.getContext("2d");和 ctx2 = canvas.getContext("2d");在 init() 函数中。如果我这样做,我认为我必须编写函数 double 例如 draw() 函数一个具有 ctx1 和另一个具有 ctx2
-
我添加了一个您可以尝试的选项的答案
标签: javascript html canvas html5-canvas