网络编程 
首页 > 网络编程 > 浏览文章

基于JavaScript canvas绘制贝塞尔曲线

(编辑:jimmy 日期: 2024/11/17 浏览:3 次 )

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

效果图:

基于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="/UploadFiles/2021-04-02/max.js">

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

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

上一篇:微信小程序实现文字跑马灯
下一篇:基于js Canvas实现二次贝塞尔曲线
Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。