温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

基于JavaScript canvas绘制贝塞尔曲线

发布时间:2020-08-26 21:32:06 来源:脚本之家 阅读:295 作者:青珣墨笠 栏目:web开发

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

效果图:

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

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI