我正在研究必须在网页上创建类似画笔的效果的功能。
要求是背景中有多种可用的图案/纹理。用户将拖动鼠标以在页面上创建该图案的效果。
下面是JSFiddle链接,我在其中创建了结构,我能够创建图案,但我不确定如何创建画笔状效果。
JSFiddle Link
中的数据源
我是画布初学者,不知道如何继续前进。请让我知道我的方向是否正确。
Reference Website
。
对于基本的画笔效果,您可以绘制一堆较小的点,而不是绘制单个大点,每个点代表一个画笔描边。如果需要,您还可以为笔画添加可变宽度,但这取决于您。 这是一个基本的画笔示例,不要画圆,而是这样画: JS 小提琴
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let drawCheck = false;
ctx.strokeStyle = "#808080";
let points = 40;
let offsets = [];
let radius = 50;
let prev = {
x: -1,
y: -1
};
let curr = {
x: -1,
y: -1
};
for (let i = 0; i < points; i++) {
offsets.push([Math.random() * radius * (-1) ** i, Math.random() * radius * (-1) ** i, 1 + Math.random() * 4]);
}
function draw(x, y) {
curr.x = x;
curr.y = y;
if (drawCheck) {
if (prev.x == -1) {
offsets.forEach(offset => {
ctx.beginPath();
ctx.arc(curr.x + offset[0], curr.y + offset[1], 1, 0, 2 * Math.PI);
ctx.fill();
prev.x = curr.x;
prev.y = curr.y;
});
} else {
offsets.forEach(offset => {
ctx.lineWidth = offset[2];
ctx.beginPath();
ctx.moveTo(prev.x + offset[0], prev.y + offset[1]);
ctx.lineTo(curr.x + offset[0], curr.y + offset[1]);
ctx.stroke();
})
prev.x = curr.x;
prev.y = curr.y;
}
}
}
document.addEventListener("mousedown", (e) => drawCheck = true);
document.addEventListener("mousemove", (e) =>
draw(e.clientX, e.clientY));
document.addEventListener("mouseup", (e) => {
drawCheck = false;
prev = {
"x": -1,
"y": -1
};
});
#canvas {
border: 2px solid black;
}
<html>
<head>
</head>
<body>
<canvas id="canvas" height=320 width=600></canvas>
</body>
</html>
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let drawCheck = false;
ctx.strokeStyle = "#808080";
let points = 40;
let offsets = [];
let radius = 50;
let prev = {
x: -1,
y: -1
};
let curr = {
x: -1,
y: -1
};
for (let i = 0; i < points; i++) {
offsets.push([Math.random() * radius * (-1) ** i, Math.random() * radius * (-1) ** i, 1 + Math.random() * 4]);
}
function draw(x, y) {
curr.x = x;
curr.y = y;
if (drawCheck) {
if (prev.x == -1) {
offsets.forEach(offset => {
ctx.beginPath();
ctx.arc(curr.x + offset[0], curr.y + offset[1], 1, 0, 2 * Math.PI);
ctx.fill();
prev.x = curr.x;
prev.y = curr.y;
});
} else {
offsets.forEach(offset => {
ctx.lineWidth = offset[2];
ctx.beginPath();
ctx.moveTo(prev.x + offset[0], prev.y + offset[1]);
ctx.lineTo(curr.x + offset[0], curr.y + offset[1]);
ctx.stroke();
})
prev.x = curr.x;
prev.y = curr.y;
}
}
}
document.addEventListener("mousedown", (e) => drawCheck = true);
document.addEventListener("mousemove", (e) =>
draw(e.clientX, e.clientY));
document.addEventListener("mouseup", (e) => {
drawCheck = false;
prev = {
"x": -1,
"y": -1
};
});
#canvas {
border: 2px solid black;
}
<html>
<head>
</head>
<body>
<canvas id="canvas" height=320 width=600></canvas>
</body>
</html>