Как мне изменить цвет обводки, используя нажатие кнопки в Javascript? - PullRequest
1 голос
/ 24 мая 2019

Цвет по умолчанию для обводки пера - черный. Я так хочу, когда пользователь нажимает кнопку, цвет обводки меняется с черного на синий

Я пытался добавить javascript window.addEventListener('load', () => { до javascript function colorBlue(), но получил ошибку: `` Uncaught ReferenceError: colorBlue не определен```.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Canvas</title>
        <link href="canvas.css" rel="stylesheet">
    </head>
    <body>
        <div id="container">
            <canvas id="c"></canvas>
            <input class="button" onclick="colorBlue()" type="button" id="blue">Blue</button>   
        </div>
    </body>
    <script src="canvas.js"></script>
</html>
#c{
    border: 1px solid black;
}
#container{
    text-align: center;
}
.button{
    width:10em;
    height:5em;
    text-align: center;
}

function colorBlue(){
const c = document.querySelector("#c");
c.height = window.innerHeight;
c.width = window.innerWidth; 
const ctx = c.getContext("2d");

window.addEventListener('load', () => {

    let painting = false;

    //when mouse is clicked; paint
    function mousedown(b){
        painting = true;
        //allows for paint to appear without nedding to drag mouse
        mousemove(b);
    }
    //when mouse is not clicked; don't paint
    function mouseup(){
        painting = false;
        //resets path each time so multiple can be created
        ctx.beginPath();
    }
    function mousemove(b){
        //if not holding down the mouse; nothing happens
        if(!painting) return;
        //line-width of paint 
        ctx.lineWidth = 10;
        //roundness of paint
        ctx.lineCap = 'round';
        //change color


        //create paint wherever the mouse goes: ctx[on the canvas].lineTo[move the line to]()
        ctx.lineTo(b.clientX, b.clientY);
        //end the stroke and visualize paint
        ctx.stroke();
        //begins a new paint so that everything doesn't just stick to a fat line
        ctx.beginPath();
        //move the new line to wherever the mouse goes
        ctx.moveTo(b.clientX, b.clientY);
    }
    //starting posistion of paint line
    c.addEventListener('mousedown', mousedown);
    //ending posistion of paint line
    c.addEventListener('mouseup', mouseup);
    //whenever the mouse is moving; paint 
    c.addEventListener('mousemove', mousemove);

    })};

const c = document.querySelector("#c");
c.height = window.innerHeight;
c.width = window.innerWidth; 
const ctx = c.getContext("2d");

    let painting = false;

    function mousedown(e){
        painting = true;
        mousemove(e);
    }
    function mouseup(){
        painting = false;
        ctx.beginPath();
    }
    function mousemove(e){
        if(!painting) return; 
        ctx.lineWidth = 10;
        ctx.lineCap = 'round';
        ctx.strokeStyle = 'black';

        ctx.lineTo(e.clientX, e.clientY);
        ctx.stroke();
        ctx.beginPath();
        ctx.moveTo(e.clientX, e.clientY);
    }
    c.addEventListener('mousedown', mousedown);
    c.addEventListener('mouseup', mouseup);
    c.addEventListener('mousemove', mousemove);

Вместо появления синих штрихов появляются только синие точки, а также кнопка сброса холста по неизвестной причине. Я ожидаю, что будут созданы синие штрихи, но вместо этого будут созданы черные.

Ответы [ 3 ]

2 голосов
/ 24 мая 2019

Вы имеете в виду что-то подобное?

function colorBlue(){
  document.getElementById("c").style.border ="1px solid blue";

}
#c{
    border: 1px solid black;
}
#container{
    text-align: center;
}
.button{
    width:10em;
    height:5em;
    text-align: center;
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Canvas</title>
        <link href="canvas.css" rel="stylesheet">
    </head>
    <body>
        <div id="container">
            <canvas id="c"></canvas>
            <input class="button" onclick="colorBlue()" type="button" id="blue">Blue</button>   
        </div>
    </body>
    <script src="canvas.js"></script>
</html>
1 голос
/ 24 мая 2019

const c = document.querySelector("#c");
c.height = window.innerHeight;
c.width = window.innerWidth;
const ctx = c.getContext("2d");
ctx.strokeStyle = "black";

window.addEventListener('load', () => {

  let painting = false;

  //when mouse is clicked; paint
  function mousedown(b) {
    painting = true;
    //allows for paint to appear without nedding to drag mouse
    mousemove(b);
  }
  //when mouse is not clicked; don't paint
  function mouseup() {
    painting = false;
    //resets path each time so multiple can be created
    ctx.beginPath();
  }

  function mousemove(b) {
    //Get correct mouse position
    var pos = getMousePos(c, b);

    //if not holding down the mouse; nothing happens
    if (!painting) return;
    //line-width of paint 
    ctx.lineWidth = 10;
    //roundness of paint
    ctx.lineCap = 'round';
    //change color


    //create paint wherever the mouse goes: ctx[on the canvas].lineTo[move the line to]()
    ctx.lineTo(pos.x, pos.y);
    //end the stroke and visualize paint
    ctx.stroke();
    //begins a new paint so that everything doesn't just stick to a fat line
    ctx.beginPath();
    //move the new line to wherever the mouse goes
    ctx.moveTo(pos.x, pos.y);
  }
  //starting posistion of paint line
  c.addEventListener('mousedown', mousedown);
  //ending posistion of paint line
  c.addEventListener('mouseup', mouseup);
  //whenever the mouse is moving; paint 
  c.addEventListener('mousemove', mousemove);

});

function colorBlue() {
  ctx.strokeStyle = "blue";
}

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: evt.clientX - rect.left,
    y: evt.clientY - rect.top
  };
}
#c {
  border: 1px solid black;
}

#container {
  text-align: center;
}

.button {
  width: 10em;
  height: 5em;
  text-align: center;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Canvas</title>
  <link href="canvas.css" rel="stylesheet">
</head>

<body>
  <div id="container">
    <canvas id="c"></canvas>
    <input class="button" onclick="colorBlue()" type="button" id="blue" value="Blue">
  </div>
</body>
<script src="canvas.js"></script>

</html>

Будьте осторожны с закрывающими скобками. В вашем коде функция colorBlue () открыта и никогда не закрывается.

Как упоминает @alifallahi, для изменения цвета обводки вам просто нужно изменить контекст strokeStyle на любой нужный вам цвет.

Кроме того, когда страница прокручивается вниз, ваш код отображает неправильные координаты холста. Как указано @ user1693593 , используйте следующую функцию, чтобы получить положение мыши относительно холста.

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
    };
}

Наконец, проверьте ссылку для элемента типа кнопки ввода. Не следует закрывать тег, который ни в коем случае не является </button>, а вместо этого использовать атрибут value для определения текста кнопки.

<input class="button" onclick="colorBlue()" type="button" id="blue" value="Blue">
0 голосов
/ 24 мая 2019

обновление colorBlue функция, как показано ниже

function colorBlue(){
ctx.strokeStyle = 'blue';
};

и комментарий ctx.strokeStyle в mousemove (e) , как показано ниже

//ctx.strokeStyle = 'black';
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...