在 元素 上实现平滑的草图绘制和绘图

问题描述 投票:29回答:7
我正在尝试使用画布创建绘图区域。我在绘制曲线时难以使线条看起来平滑,并且在算法中也更改了线条粗细,这看起来也很糟糕,因为尺寸也会跳到很多,并且可以看到尺寸发生了变化。我确实找到了此link on stackoverflow,但这是用于本机iPhone应用程序的,我无法弄清楚。

这是我当前的JS代码。并在这里运行on jsFiddle

var xStart, xEnd, yStart, yEnd, paint, ctx; $(document).ready(function (){ ctx = $('canvas')[0].getContext("2d"); ctx.strokeStyle = '#000'; ctx.lineJoin="round"; ctx.lineCap="round"; ctx.lineWidth = 1; $('canvas').bind('mousedown mousemove mouseup mouseleave touchstart touchmove touchend', function(e){ var orig = e.originalEvent; if(e.type == 'mousedown'){ e.preventDefault(); e.stopPropagation(); xStart = e.clientX - $(this).offset().left; yStart = e.clientY - $(this).offset().top; xEnd = xStart; yEnd = yStart; paint = true; draw(e.type); }else if(e.type == 'mousemove'){ if(paint==true){ xEnd = e.clientX - $(this).offset().left; yEnd = e.clientY - $(this).offset().top; lineThickness = 1 + Math.sqrt((xStart - xEnd) *(xStart-xEnd) + (yStart - yEnd) * (yStart-yEnd))/5; if(lineThickness > 10){ lineThickness = 10; } ctx.lineWidth = lineThickness; draw(e.type); } }else if(e.type == 'mouseup'){ paint = false; }else if(e.type == 'mouseleave'){ paint = false; }else if(e.type == 'touchstart'){ if(orig.touches.length == 1){ e.preventDefault(); e.stopPropagation(); xStart = orig.changedTouches[0].pageX - $(this).offset().left; yStart = orig.changedTouches[0].pageY - $(this).offset().top; xEnd = xStart; yEnd = yStart; paint = true; draw(e.type); } }else if(e.type == 'touchmove'){ if(orig.touches.length == 1){ if(paint==true){ xEnd = orig.changedTouches[0].pageX - $(this).offset().left; yEnd = orig.changedTouches[0].pageY - $(this).offset().top; lineThickness = 1 + Math.sqrt((xStart - xEnd) *(xStart-xEnd) + (yStart - yEnd) * (yStart-yEnd))/6; if(lineThickness > 10){ lineThickness = 10; } ctx.lineWidth = lineThickness; draw(e.type); } } }else if(e.type == 'touchend'){ paint = false; } }); }); function draw(event){ if(event == 'mousedown'){ ctx.beginPath(); ctx.moveTo(xStart, yStart); ctx.lineTo(xEnd, yEnd); ctx.stroke(); }else if(event == 'mousemove'){ ctx.beginPath(); ctx.moveTo(xStart, yStart); ctx.lineTo(xEnd, yEnd); ctx.stroke(); }else if(event == 'touchstart'){ ctx.beginPath(); ctx.moveTo(xStart, yStart); ctx.lineTo(xEnd, yEnd); ctx.stroke(); }else if(event == 'touchmove'){ ctx.beginPath(); ctx.moveTo(xStart, yStart); ctx.lineTo(xEnd, yEnd); ctx.stroke(); } xStart = xEnd; yStart = yEnd; }

谢谢大家。 

这就是现在绘制的样子。 “当前(锯齿状)实现”

...这就是我想要实现的目标:

“平滑的笔触”

我正在尝试使用画布创建绘图区域。我在绘制曲线时难以使线条看起来平滑,并且在算法中也改变了线的粗细,因为...

javascript html canvas drawing paint
7个回答
22
投票
我前一阵子做了这样的事情,并将其变成了jquery插件。看看这里,如果您要这样做的话,我将发布更详细的答案,并从我的档案中挖掘出简化的jquery版本:

9
投票
查看此代码:

6
投票
您为什么不使用croquis.js

2
投票
似乎您需要在画布中使用某些

brushes


2
投票
建议通过围绕周围填充的曲线的一串贝塞尔曲线进行渲染。 (即以ctx.fill结尾)仍有大量工作要做,但希望能有所帮助。

2
投票
对于那些对@Alex提供的代码的点击版本感兴趣的人,我在这里重写了他的脚本:

0
投票
重要!
© www.soinside.com 2019 - 2024. All rights reserved.