如何在没有 ctx.bezierCurveTo 的情况下使用原生 Javascript 代码绘制 Bezier 曲线?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16227300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:47:48  来源:igfitidea点击:

How to draw Bezier curves with native Javascript code without ctx.bezierCurveTo?

javascriptuibezierpath

提问by Digerkam

I need to draw and get coordinates of bezier curves of each steps with native Javascript without ctx.bezierCurveTo method.

我需要在没有 ctx.bezierCurveTo 方法的情况下使用原生 Javascript 绘制和获取每个步骤的贝塞尔曲线的坐标。

I found several resources, but I confused. Esspecially thislooks pretty close, but I couldnt implemented clearly.

我找到了几个资源,但我很困惑。特别是看起来很接近,但我无法清楚地实施。

How can I accomplish this?

我怎样才能做到这一点?

回答by hobberwickey

You can plot out the Bezier:

您可以绘制贝塞尔曲线:

bezier = function(t, p0, p1, p2, p3){
  var cX = 3 * (p1.x - p0.x),
      bX = 3 * (p2.x - p1.x) - cX,
      aX = p3.x - p0.x - cX - bX;

  var cY = 3 * (p1.y - p0.y),
      bY = 3 * (p2.y - p1.y) - cY,
      aY = p3.y - p0.y - cY - bY;

  var x = (aX * Math.pow(t, 3)) + (bX * Math.pow(t, 2)) + (cX * t) + p0.x;
  var y = (aY * Math.pow(t, 3)) + (bY * Math.pow(t, 2)) + (cY * t) + p0.y;

  return {x: x, y: y};
},

(function(){
  var accuracy = 0.01, //this'll give the bezier 100 segments
      p0 = {x: 10, y: 10}, //use whatever points you want obviously
      p1 = {x: 50, y: 100},
      p2 = {x: 150, y: 200},
      p3 = {x: 200, y: 75},
      ctx = document.createElement('canvas').getContext('2d');

  ctx.width = 500;
  ctx.height = 500;
  document.body.appendChild(ctx.canvas);

  ctx.moveTo(p0.x, p0.y);
  for (var i=0; i<1; i+=accuracy){
     var p = bezier(i, p0, p1, p2, p3);
     ctx.lineTo(p.x, p.y);
  }

  ctx.stroke()
})()

Here's a fiddle http://jsfiddle.net/fQYsU/

这是一个小提琴http://jsfiddle.net/fQYsU/