当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 基于JavaScript canvas绘制贝塞尔曲线

基于JavaScript canvas绘制贝塞尔曲线

2019年06月01日  | 移动技术网IT编程  | 我要评论

简单描述:页面上有四个点,鼠标拖动四个点的位置来改变贝塞尔曲线的形状,双击放置点位

效果图:

代码:

<!doctype html>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>title</title>
  <style>
   html{overflow: hidden;}
   * {padding: 0;margin: 0;}
   #box {background-color: #000000;}
   .point {
    width: 20px;
    height: 20px;
    background-color: #fff;
    border-radius: 50%;
    position: absolute;
    left: 100px;
    top:200px;
    text-align: center;
    line-height: 20px;
   }
  </style>
 </head>
 <body>
  <canvas id="box"></canvas>

  <div class="point startpoint">b</div>
  <div class="point endpoint">e</div>
  <div class="point point1">1</div>
  <div class="point point2">2</div>
 <script src="js/max.js"></script>
 </body>
</html>

js:

/**
 * created by administrator on 2017/8/11.
 * js/max.js
 */
(function () {
 var curele = null;
 var startpointview = document.queryselector(".startpoint");
 var endpointpointview = document.queryselector(".endpoint");
 var point1view = document.queryselector(".point1");
 var point2view = document.queryselector(".point2");
 var context = null;
 function init() {
  var canvasele = document.queryselector("#box");
  canvasele.width = innerwidth;
  canvasele.height = innerheight;
  //实时监听网页大小
  window.onresize = function () {
   canvasele.width = innerwidth;
   canvasele.height = innerheight;
  };
  context = canvasele.getcontext("2d");

  context.strokestyle = "white";
  context.linewidth = 10;
  //贝塞尔曲线简单用法
  context.beginpath();
  context.moveto(300,300);
  context.beziercurveto(500,200,600,250,600,600);
  context.stroke();
  //循环获取四个点的数组
  for(var i=0;i<4;i++){
  addevent([startpointview,endpointpointview,point1view,point2view][i]);
  }
  //鼠标双击移除鼠标滑动事件 放下拖动的点
  document.ondblclick = function () {
   document.removeeventlistener("mousemove",move);
  };
 }
 //鼠标按下拖动
 function addevent(ele) {
  ele.onmousedown = function () {
   curele = this;
   document.addeventlistener("mousemove",move);
  };
 }
 //获取拖动位置并绘制贝塞尔曲线
 function move(event) {
  curele.style.left = event.pagex+"px";
  curele.style.top = event.pagey+"px";
  context.clearrect(0,0,innerwidth,innerheight);
  context.beginpath();
  context.moveto(getleft(startpointview),gettop(startpointview));
  context.beziercurveto(getleft(point1view),gettop(point1view),getleft(point2view),gettop(point2view),getleft(endpointpointview),gettop(endpointpointview));
  context.stroke();
 }
 function getleft(ele) {
  return parseint(ele.style.left);
 }
 function gettop(ele) {
  return parseint(ele.style.top);
 }
 init();
})();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网