javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > canvas绘制贝塞尔曲线

基于JavaScript canvas绘制贝塞尔曲线

作者:青珣墨笠

这篇文章主要为大家详细介绍了基于JavaScript canvas绘制贝塞尔曲线的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

效果图:

代码:

<!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();
})();

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

您可能感兴趣的文章:
阅读全文