简体   繁体   中英

Javascript canvas change drawing color

I am making a simple drawing board with HTML and JavaScript (Node as server side), but I don't know how I can make a colorpicker where I change the color of the paint. I know how to hard code it, but that is not what I want.

I want something like buttons, if you click a button it will turn into a specific color. Something like 4 buttons.

This is my method:

 //Function for when the mouse button is clicked.
canvas.onmousedown = function (e) {
    //The mouse button is clicked (true).
    mouse.click = true;
    context.strokeStyle = "red";
};

As you can see, I have hardcoded the color to red.

This is my full JavaScript code. The HTML document only consist of an element "canvas".

//"DOMContetLoaded tells the browser then the HTML page has finished loading.
document.addEventListener("DOMContentLoaded", function () {
    //Add standard mouse functions.
    var mouse = {
        click: false,
        move: false,
        pos: { x: 0, y: 0 },
        pos_prev: false
    };

    //Get the CanvasWhiteboard elements by it's ID from the HTML page. We need this to be able to draw.
    var canvas = document.getElementById('whiteboard');
    //The whiteboard is in 2D with the width and height being the dimensions of the window.
    var context = canvas.getContext('2d');
    var width = window.innerWidth;
    var height = window.innerHeight;

    //The client connects to the server.
    var socket = io.connect();

    //The width and height of the whiteboard equals the window width and height.
    canvas.width = width;
    canvas.height = height;

    // Function for when the mouse button is pushed down.
    canvas.onmousedown = function (e) {
        // Set mouse click to true.
        mouse.click = true;
        context.strokeStyle = "red";
    };

    // Function for when the mouse button is lifted.
    canvas.onmouseup = function (e) {
        // Set mouse click to false.
        mouse.click = false;
    };

    // Function to check if the mouse is moved.
    canvas.onmousemove = function (e) {
        //The movement of the mouse at X and Y position is updated everytime the mouse moves.
        //The coordinates equals the coordinates relative to the window height and width.
        mouse.pos.x = e.clientX / width;
        mouse.pos.y = e.clientY / height;

        //The mouse is moving (true).
        mouse.move = true;
    };

    //Listen for draws from other clients.
    socket.on('draw_data', function (data) {
        //The line being drawn equals the data.
        var line = data.line;

        //Begin from the start of the drawn data.
        context.beginPath();

        //The thickness of the line.
        context.lineWidth = 2;

        //Next point to move to from the beginPath.
        context.moveTo(line[0].x * width, line[0].y * height);

        //End point to move to from the beginPath.
        context.lineTo(line[1].x * width, line[1].y * height);

        //The data is then drawn on the whiteboard.
        context.stroke();
    });

    //This loop is where our own drawings are sent to the server for the other clients to see.
    //It checks every 25ms if the mouse is being clicked and moved.
    function mainLoop() {
        if (mouse.click && mouse.move && mouse.pos_prev) {
            //Send our drawing to the server.
            socket.emit('draw_data', { line: [mouse.pos, mouse.pos_prev] });
            //The mouse movement is set to false (reset).
            mouse.move = false;
        }

        //The previous position now equals the position we just were at.
        mouse.pos_prev = { x: mouse.pos.x, y: mouse.pos.y };

        //This is where the 25ms is definend.
        setTimeout(mainLoop, 25);
    }

    //Being called recursively.
    mainLoop();
});

You can use CSS to do it too, changing the Canvas to red when click the button

 canvas{
      background-color:red; 
 }

Or try this code:

     //Function for when the mouse button is clicked.
canvas.onmousedown = function (e) {
    //The mouse button is clicked (true).
    mouse.click = true;
    ctx.fillStyle = 'red';
};

This was my solution:

In HTML I added a drop down box:

 <!--Color Picker-->
<select id="colors">
    <option value="black">black</option>
    <option value="aqua">aqua</option>
    <option value="blue">blue</option>
    <option value="brown">brown</option>
</select>

In my JavaScript I added this to get the color picker by ID:

//Get the color picker from the HTML page by ID.
var getColorPickerByID = document.getElementById("colors");

And this to get the value of the color picker, ie the selected item. This should of course be in a loop that updates every like 10ms so the value gets updated when you pick a new color:

//Get the color picker value, i.e. if the user picks red the value is red.
var getValueOfColorPicker = getColorPickerByID.options[getColorPickerByID.selectedIndex].text;

And at last the strokeStyle itself to set the color of the line being drawn by using the value from the above variable getValueOfColorPicker

//Set the color of the line being drawn by using above variable "getValueOfColorPicker".
drawingArea.strokeStyle = getValueOfColorPicker;

I written sample code you can use it.

 function changeColor(color) { ctx.strokeStyle = color; }; const c = document.querySelector("#c"); c.height = window.innerHeight / 2; c.width = window.innerWidth / 2; 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 = 4; ctx.lineCap = 'round'; //ctx.strokeStyle = 'black'; ctx.lineTo(e.clientX / 2, e.clientY / 2); ctx.stroke(); ctx.beginPath(); ctx.moveTo(e.clientX / 2, e.clientY / 2); } c.addEventListener('mousedown', mousedown); c.addEventListener('mouseup', mouseup); c.addEventListener('mousemove', mousemove);
 #c { border: 1px solid black; } #container { text-align: center; } .button { width: 5em; height: 2em; text-align: center; }
 <html> <head> <meta charset="utf-8" content="Badri,Chorapalli,XML,JavaScript"> <title>Canvas</title> </head> <body> <div id="container"> <canvas id="c" width="400" height="400"></canvas><br> <button class="button" onclick="changeColor('black')" id="blue">Black</button> <button class="button" onclick="changeColor('blue')" id="blue">Blue</button> <button class="button" onclick="changeColor('red')" id="blue">Red</button> <button class="button" onclick="changeColor('green')" id="blue">Green</button> </div> </body> </html>

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