javascript холст. переключаться между глобальной композиционной операцией - PullRequest
1 голос
/ 30 апреля 2020

Я разрабатываю бесплатный холст для рисования. у него есть два инструмента. брю sh для рисования и ластика. по умолчанию выбран bru sh и пользователь может рисовать. выбирая ластик из выпадающего меню, я изменяю «globalcompositeoperation» на «destination-out»; и пользователь может стереть. пока все хорошо. но когда пользователь переключает инструмент обратно в режим bru sh, (ctx.globalcompositeoperation = "source-over") не вступает в силу, и ластик остается активным всегда! Как правильно переключаться между bru sh и ластиком. спасибо

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    Tool:
    <select id="tool">
      <option value="brush">Brush</option>
      <option value="eraser">Eraser</option>
    </select>
    <canvas id="canvas"></canvas>
    <script>
        window.addEventListener("load", () => {
  const canvas = document.getElementById("canvas");
  const ctx = canvas.getContext("2d");
  canvas.height = window.innerHeight - 8;
  canvas.width = window.innerWidth - 8;
  ctx.strokeStyle = "black";
  ctx.lineWidth = 10;
    ctx.shadowBlur = 10;
    ctx.shadowColor = "rgb(0, 0, 0)";
    ctx.lineJoin = "round";
    ctx.lineCap = "round";
  let painting = false;
  function startPosition(e) {
    painting = true;
    draw(e);
  }
  function finishedPosition() {
    painting = false;
    ctx.beginPath();
  }
  function draw(e) {
    if (!painting) return;
    ctx.lineTo(e.clientX, e.clientY);
    ctx.stroke();
  }
  canvas.addEventListener("mousedown", startPosition);
  canvas.addEventListener("mouseup", finishedPosition);
  canvas.addEventListener("mousemove", draw);
  var select = document.getElementById("tool");
  select.addEventListener("change", function () {
    mode = select.value;
    if (mode == "brush") {
      // this can't bring brush back!
      ctx.globalcompositeoperation = "source-over";
      console.log("brush");
    } else {
      // this changes brush to eraser successfully
      ctx.globalCompositeOperation = "destination-out";
      ctx.globalcompositeoperation = "source-over";
      console.log("eraser");
    }
  });
});
    </script>

</body>
</html>

Ответы [ 2 ]

1 голос
/ 01 мая 2020

Похоже, что у вас есть опечатка globalCompositeOperation.
Помните JavaScript это регистрозависимый язык.

вот ваш рабочий код:

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.height = window.innerHeight - 8;
canvas.width = window.innerWidth - 8;
ctx.strokeStyle = "black";
ctx.lineWidth = ctx.shadowBlur = 10;
ctx.shadowColor = "rgb(0, 0, 0)";
ctx.lineJoin = ctx.lineCap = "round";
let painting = false;

function startPosition(e) {
  painting = true;
  draw(e);
}

function finishedPosition() {
  painting = false;
  ctx.beginPath();
}

function draw(e) {
  if (!painting) return;
  ctx.lineTo(e.clientX, e.clientY);
  ctx.stroke();
}

canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mouseup", finishedPosition);
canvas.addEventListener("mousemove", draw);

var select = document.getElementById("tool");
select.addEventListener("change", function() {
  mode = select.value;
  if (mode == "brush") {
    ctx.globalCompositeOperation = "source-over";
  } else {
    ctx.globalCompositeOperation = "destination-out";
  }
});
<!DOCTYPE html>
<html lang="en">

<body>
  Tool:
  <select id="tool">
    <option value="brush">Brush</option>
    <option value="eraser">Eraser</option>
  </select>
  <canvas id="canvas"></canvas>
</body>

</html>
0 голосов
/ 01 мая 2020

если выписка была не в том месте!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        #c{
            border: 2px black solid;
        }
    </style>
</head>
<body>
    Tool:
    <select id="tool">
      <option value="brush">Brush</option>
      <option value="eraser">Eraser</option>
    </select>
    <canvas id="canvas"></canvas>
    <!-- <canvas id="c" width="500" height="300"></canvas> -->
    <!-- <script src="./canvas.js"></script> -->
    <script>
        window.addEventListener("load", () => {
  const canvas = document.getElementById("canvas");
  const ctx = canvas.getContext("2d");
  canvas.height = window.innerHeight - 8;
  canvas.width = window.innerWidth - 8;
  ctx.strokeStyle = "black";
  ctx.lineWidth = 10;
    ctx.shadowBlur = 10;
    ctx.shadowColor = "rgb(0, 0, 0)";
    ctx.lineJoin = "round";
    ctx.lineCap = "round";
  let painting = false;
  let mode = 'brush'
  function startPosition(e) {
    painting = true;
    draw(e);
  }
  function finishedPosition() {
    painting = false;
    ctx.beginPath();
  }
  function draw(e) {
    if (!painting) return;
    if(mode=='brush') {
        ctx.globalCompositeOperation = 'source-over';
        ctx.strokeStyle = 'black';
        ctx.lineWidth = 3;
    } else {
        ctx.globalCompositeOperation = 'destination-out';
        ctx.lineWidth = 10;
    }
    ctx.lineTo(e.clientX, e.clientY);
    ctx.stroke();
  }
  canvas.addEventListener("mousedown", startPosition);
  canvas.addEventListener("mouseup", finishedPosition);
  canvas.addEventListener("mousemove", draw);
  var select = document.getElementById("tool");
  select.addEventListener("change", function () {
    mode = select.value;
  });
});
    </script>
</body>
</html>
...