Javascript画布更改绘图颜色

Javascript画布更改绘图颜色,javascript,html,Javascript,Html,我正在用HTML和JavaScript(节点作为服务器端)制作一个简单的绘图板,但我不知道如何制作一个颜色选择器,在这里我可以更改油漆的颜色。我知道如何硬编码,但这不是我想要的 我想要一些像按钮的东西,如果你点击一个按钮,它会变成一种特定的颜色。大约4个按钮 这是我的方法: //Function for when the mouse button is clicked. canvas.onmousedown = function (e) { //The mouse button is

我正在用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文档只包含一个元素“canvas”


您也可以使用CSS来执行此操作,单击按钮时将画布更改为红色

 canvas{
      background-color:red; 
 }
或者尝试以下代码:

     //Function for when the mouse button is clicked.
canvas.onmousedown = function (e) {
    //The mouse button is clicked (true).
    mouse.click = true;
    ctx.fillStyle = 'red';
};
这就是我的解决方案:

在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>
这将获得颜色选择器的值,即所选项目。当然,这应该是一个循环,每10毫秒更新一次,以便在选择新颜色时更新值:

//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;

我写的示例代码你可以使用它

函数更改颜色(颜色){
ctx.strokeStyle=颜色;
};
const c=document.querySelector(“#c”);
c、 高度=窗内高度/2;
c、 宽度=window.innerWidth/2;
const ctx=c.getContext(“2d”);
让绘画=虚假;
功能鼠标向下(e){
绘画=真实;
mousemove(e);
}
函数mouseup(){
绘画=假;
ctx.beginPath();
}
函数mousemove(e){
如果(!喷漆)返回;
ctx.lineWidth=4;
ctx.lineCap='圆形';
//ctx.strokeStyle=‘黑色’;
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{
边框:1px纯黑;
}
#容器{
文本对齐:居中;
}
.按钮{
宽度:5em;
高度:2米;
文本对齐:居中;
}

帆布

黑色 蓝色 红色 绿色
除非我弄错了,否则这与
nodeJs
没有任何关系。很抱歉,你是对的,这是javascript,我改变了问题。如果你不想硬编码颜色,你想从哪里获得颜色?如果你要我们帮助你实现颜色选择器,这个问题太广泛了(也可能会有相关的问题,以便有答案)。如果您要求我们推荐一个第三方颜色选择器,这与SO无关。我想要按钮之类的东西,如果您单击一个按钮,它将变成特定的颜色。类似于4个按钮。抱歉,这不是画布颜色,而是绘图颜色。
//Get the color picker value, i.e. if the user picks red the value is red.
var getValueOfColorPicker = getColorPickerByID.options[getColorPickerByID.selectedIndex].text;
//Set the color of the line being drawn by using above variable "getValueOfColorPicker".
drawingArea.strokeStyle = getValueOfColorPicker;