首先我想说我做了很多研究和尝试,但没有成功。
我正在使用 Canvas 开发类似 MSPaint 的应用程序,我想创建一个看起来像手工绘图一样逼真的铅笔工具...这是下面链接中的示例默认工具: http://www.onemotion.com/flash/sketch-paint/
我尝试使用 mousespeed 和 linewidth 属性,但效果不佳(移动鼠标时整条线会放大和缩小)。我不知道作用于像素原始数据的算法。
您知道现有的东西或适合应用的算法吗?非常感谢您的帮助
编辑
我决定添加我选择的解决方案,因为很多人似乎对它感兴趣。 所以,到目前为止我发现的最好的方法是使用此处解释的技术在 Canvas 上绘制图像:http://css.dzone.com/articles/sketching-html5-canvas-and . 它就像一个魅力,结果真的很有说服力,而且很容易实现。在这里试试:http://tricedesigns.com/portfolio/sketch/brush.html#
最佳答案
你可以试试下面的demo
您最有可能使用 moveTo
和 lineTo
来创建路径,如果您这样做,属性将共享路径直到您关闭路径。因此,每次更改厚度时,您都需要调用 closePath
,然后再次调用 beginPath
。
在我的示例中,我使用 Bresenham's line algorithm绘制点。基本上在鼠标按下时它开始绘画。然后 onmousemove 它将当前坐标与最后一个坐标进行比较,并绘制两者之间的所有点。它还使用 fillRect
进行绘制。根据您移动的速度,线会变粗或变细。
下面是绘图函数的代码
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
painting = false,
lastX = 0,
lastY = 0,
lineThickness = 1;
canvas.width = canvas.height = 600;
ctx.fillRect(0, 0, 600, 600);
canvas.onmousedown = function(e) {
painting = true;
ctx.fillStyle = "#ffffff";
lastX = e.pageX - this.offsetLeft;
lastY = e.pageY - this.offsetTop;
};
canvas.onmouseup = function(e){
painting = false;
}
canvas.onmousemove = function(e) {
if (painting) {
mouseX = e.pageX - this.offsetLeft;
mouseY = e.pageY - this.offsetTop;
// find all points between
var x1 = mouseX,
x2 = lastX,
y1 = mouseY,
y2 = lastY;
var steep = (Math.abs(y2 - y1) > Math.abs(x2 - x1));
if (steep){
var x = x1;
x1 = y1;
y1 = x;
var y = y2;
y2 = x2;
x2 = y;
}
if (x1 > x2) {
var x = x1;
x1 = x2;
x2 = x;
var y = y1;
y1 = y2;
y2 = y;
}
var dx = x2 - x1,
dy = Math.abs(y2 - y1),
error = 0,
de = dy / dx,
yStep = -1,
y = y1;
if (y1 < y2) {
yStep = 1;
}
lineThickness = 5 - Math.sqrt((x2 - x1) *(x2-x1) + (y2 - y1) * (y2-y1))/10;
if(lineThickness < 1){
lineThickness = 1;
}
for (var x = x1; x < x2; x++) {
if (steep) {
ctx.fillRect(y, x, lineThickness , lineThickness );
} else {
ctx.fillRect(x, y, lineThickness , lineThickness );
}
error += de;
if (error >= 0.5) {
y += yStep;
error -= 1.0;
}
}
lastX = mouseX;
lastY = mouseY;
}
}
关于javascript - 使用 HTML5 Canvas 为绘画应用创建逼真的铅笔工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10122553/