简单描述:页面上有四个点,鼠标拖动四个点的位置来改变贝塞尔曲线的形状,双击放置点
简单描述:页面上有四个点,鼠标拖动四个点的位置来改变贝塞尔曲线的形状,双击放置点位
效果图:
代码:
<!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();
})();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
js canvas 贝塞尔曲线