简体   繁体   中英

How do I change the color of a stroke using the click of a button in Javascript?

The default color of a pen stroke is black. I want it so when the user presses the button, the stroke color changes from black to blue

I tried to add an javascript window.addEventListener('load', () => { before javascript function colorBlue() , but I got the error: ``Uncaught ReferenceError: colorBlue is not defined```.

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

Instead of blue strokes appearing, only blue dots do, as well as the button resetting the canvas for an unknown reason. I expect that blue strokes be created but black ones are created instead.

Do you mean something like this?

 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> 

 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> 

Be careful with closing brackets. In your code the colorBlue() function is open and never closed.

As @alifallahi mention, to change the stroke color you just need to change the context strokeStyle to whatever color you need.

Also, when the page is scrolled down, your code draws in the wrong canvas coordinates. As mentioned by @user1693593 , use the following function to get the mouse position relative to the canvas.

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

Lastly, check the reference for the input button type element. You shouldn't close the tag, that, in any way is not </button> , and instead use the value attribute to define the button text.

<input class="button" onclick="colorBlue()" type="button" id="blue" value="Blue">

update colorBlue function as below

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

and comment ctx.strokeStyle in mousemove(e) function as below

//ctx.strokeStyle = 'black';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM