JavaScript画布更改绘图颜色

时间:2018-11-08 13:06:56

标签: javascript html

我正在用HTML和JavaScript(节点作为服务器端)制作一个简单的绘图板,但是我不知道如何在更改油漆颜色的地方制作颜色选择器。我知道如何对其进行硬编码,但这不是我想要的。

我想要按钮之类的东西,如果单击按钮,它将变成特定的颜色。大约有4个按钮。

这是我的方法:

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

如您所见,我已将颜色硬编码为红色。

这是我的完整JavaScript代码。 HTML文档仅包含元素“画布”。

//"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();
});

3 个答案:

答案 0 :(得分:1)

您也可以使用CSS来做,单击按钮时将Canvas更改为红色

reference

或尝试以下代码:

 canvas{
      background-color:red; 
 }

答案 1 :(得分:0)

这是我的解决方案:

在HTML中,我添加了一个下拉框:

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

在我的JavaScript中,我添加了此代码以通过ID获得颜色选择器:

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

这将获取颜色选择器(即所选项目)的值。当然,这应该是一个循环,每10ms更新一次,以便在您选择新颜色时更新该值:

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

最后,strokeStyle本身使用上面的变量getValueOfColorPicker的值来设置要绘制的线条的颜色

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

答案 2 :(得分:0)

我编写了示例代码,您可以使用它。

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>