您好我想在我的项目中使用自定义的defind颜色而不是使用随机颜色,因为其中一些颜色在我的背景上不可见。我的背景不是白色,所以我怎么能实现这个目标。
我想创建一个下拉列表,我可以从中选择颜色和绘制图层,或者可以在randomcolors函数中自定义颜色。
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var isDown = false;
var startY;
var layers = [];
var currentColor = "black";
function handleMouseDown(e) {
e.preventDefault();
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
currentColor = randomColor();
isDown = true;
}
function handleMouseUp(e) {
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
isDown = false;
layers.push({
y1: startY,
y2: mouseY,
color: currentColor
});
}
function handleMouseOut(e) {
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
isDown = false;
layers.push({
y1: startY,
y2: mouseY,
color: currentColor
});
}
function handleMouseMove(e) {
if (!isDown) {
return;
}
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
drawAll();
hLine(startY, currentColor);
hLine(mouseY, currentColor);
}
function drawAll() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < layers.length; i++) {
layer = layers[i];
hLine(layer.y1, layer.color);
hLine(layer.y2, layer.color);
}
}
function hLine(y, color) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
ctx.strokeStyle = color;
ctx.stroke();
}
function randomColor() {
return ('#' + Math.floor(Math.random() * 16777215).toString(16));
}
$("#canvas").mousedown(function (e) {
handleMouseDown(e);
});
$("#canvas").mousemove(function (e) {
handleMouseMove(e);
});
$("#canvas").mouseup(function (e) {
handleMouseUp(e);
});
$("#canvas").mouseout(function (e) {
handleMouseOut(e);
});
答案 0 :(得分:2)
您可以添加带颜色的选项,如下所示:
<select id="cmbColor">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
然后,在随机颜色函数中,返回它(并更改函数的名称)
function randomColor() {
return document.getElementById("cmbColor").value;
}
将绘制的线将是选择颜色!
编辑:
使用html5,您甚至可以像这样添加和输入:
<input id="txtColor" type="color">
它会提示用户使用颜色选择器表格! (仅适用于html5)
答案 1 :(得分:0)
您将要更改此行代码currentColor = randomColor();
可以在此处找到:
function handleMouseDown(e) {
e.preventDefault();
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
currentColor = randomColor(); //<---- Right Here//
isDown = true;
}
例如,某些内容如:currentColor = 'red';
会为您提供:http://jsfiddle.net/Vnsx6/
答案 2 :(得分:0)
只需为select
创建一个输入,然后通过jQuery
使用该值
<select id="pickCol">
<option value="#FF0000">Red</option>
<option value="#0000FF">Blue</option>
<option value="#00FF00">Green</option>
</select>
和JS:
currentColor = $("#pickCol").val();