简体   繁体   English

HTML5画布javascript逐渐变细画笔

[英]HTML5 canvas javascript tapering brush

I need create nice and smooth tapering brush like this: 我需要像这样创建漂亮而光滑的渐变画笔: 在此输入图像描述

But i have problem with mouse speed movement. 但我有鼠标速度运动的问题。 how to make brush tapering no dependency with mouse movement speed. 如何使画笔逐渐变细,与鼠标移动速度无关。 I need make brush tapering which not different then mouse move very fast and slow. 我需要使刷子逐渐变细,然后鼠标移动得非常快和慢。

Now with diferrent speed i get this results: 现在速度不同,我得到了这个结果: 在此输入图像描述

  var el = document.getElementById('c'); var ctx = el.getContext('2d'); var isDrawing, lastPoint; ctx.lineWidth = 20; el.onmousedown = function(e) { isDrawing = true; lastPoint = { x: e.clientX, y: e.clientY }; ctx.lineWidth = 20; }; el.onmousemove = function(e) { if (!isDrawing) return; ctx.lineJoin = "round"; ctx.lineCap = "butt"; ctx.strokeStyle = "#000000"; ctx.globalAlpha = "1"; ctx.globalCompositeOperation = "source-over"; if(ctx.lineWidth >= 5) { ctx.lineWidth -= 0.1; } var currentPoint = { x: e.clientX, y: e.clientY }; ctx.beginPath(); ctx.moveTo(lastPoint.x, lastPoint.y); ctx.lineTo(currentPoint.x, currentPoint.y); ctx.closePath(); ctx.stroke(); lastPoint = currentPoint; }; el.onmouseup = function() { isDrawing = false; }; function clearit() { ctx.clearRect(0,0, 1000, 1000); } 
  canvas { border: 1px solid #ccc } 
 <canvas id="c" width="500" height="500"></canvas> 

Instead of drawing the tapered stroke using mousemove , use mousedown to start a new stroke and use mouseup to end that new stroke. 不使用mousemove绘制渐变笔划,而是使用mousedown开始新笔划并使用mouseup结束新笔划。 Use an array to collect all the mouse positions between mousedown and mouseup. 使用数组收集mousedown和mouseup之间的所有鼠标位置。

After mouseup you can calculate the distance the mouse has traveled since mousedown and draw a tapered polyline over that distance. mouseup就可以计算出,因为鼠标按下鼠标已经移动的距离和在该距离绘制折线锥形。 You can use linear interpolation to calculate a smooth transition of the lineWidth from start to end. 您可以使用线性插值来计算lineWidth从开始到结束的平滑过渡。

Since you're using interpolation rather than mousemoves, the speed of the mouse will be taken out of the equation! 由于您使用的是插值而不是鼠标移动,因此鼠标的速度将被取消!

To provide feedback to the user as they are defining the line, you can draw a 1 pixel stroke during mousemove . 要在用户定义线条时向用户提供反馈,您可以在mousemove期间绘制1像素笔划。 This feedback polyline will be overwritten by the tapered polyline when they release the mouse. 当它们释放鼠标时,该反馈折线将被锥形折线覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM