<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>贝塞尔曲线</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#canvas {
border: 1px solid #02B0AD;
}
.ball {
display: block;
width: 20px;
height: 20px;
border-radius: 50%;
position: absolute;
left: 390px;
top: 390px;
cursor: pointer;
}
.ball:nth-child(1) {
background: #007AFF;
z-index: 1;
}
.ball:nth-child(2) {
background: #007AFF;
z-index: 552;
}
#box {
width: 800px;
height: 800px;
position: relative;
margin: 80px auto 0;
}
</style>
</head>
<body>
<div id="box">
<span class="ball"></span>
<span class="ball"></span>
<canvas id="canvas" width="800" height="800"></canvas>
</div>
<script type="text/javascript">
var ball = document.getElementsByClassName('ball');
var box = document.getElementById('box');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x0 = 390,
x1 = 390,
y0 = 390,
y1 = 390;
//绘制三次贝塞尔曲线
ctx.beginPath();
ctx.moveTo(0, 800);
ctx.bezierCurveTo(400, 400, 400, 400, 800, 0);
ctx.strokeStyle = 'red';
ctx.stroke();
//绘制下面切线
ctx.beginPath();
ctx.moveTo(0, 800);
ctx.lineTo(400, 400);
ctx.strokeStyle = '#007AFF';
ctx.stroke();
//绘制上面切线
ctx.beginPath();
ctx.moveTo(800, 0);
ctx.lineTo(400, 400);
ctx.strokeStyle = '#007AFF';
ctx.stroke();
//对两个按钮循环遍历
for(var i = 0; i < ball.length; i++) {
ball[i].index = i;
ball[i].onmousedown = function(e) {
//阻止浏览器默认事件
if(e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
var _this = this.index; //获取点击按钮的下标值
//按钮移动
document.onmousemove = function(e) {
ctx.clearRect(0, 0, 800, 800); //清除画布
var e = e || window.event;
var x = e.clientX - box.offsetLeft - ball[0].offsetWidth / 2;
var y = e.clientY - box.offsetTop - ball[0].offsetHeight / 2;
if(y >= canvas.height - ball[0].offsetHeight / 2) {
y = canvas.height - ball[0].offsetHeight / 2;
}
if(y <= -ball[0].offsetHeight / 2) {
y = -ball[0].offsetHeight / 2;
}
if(x >= canvas.width - ball[0].offsetWidth / 2) {
x = canvas.width - ball[0].offsetWidth / 2;
}
if(x <= -ball[0].offsetWidth / 2) {
x = -ball[0].offsetWidth / 2;
}
//判断哪个按钮被移动,并获取此按钮的移动的坐标值
if(_this == 0) {
x0 = x;
y0 = y;
} else {
x1 = x;
y1 = y;
}
//绘制三次贝塞尔曲线
ctx.beginPath();
ctx.moveTo(0, 800);
ctx.bezierCurveTo(x0 + ball[0].offsetWidth / 2, y0 + ball[0].offsetHeight / 2, x1 + ball[0].offsetWidth / 2, y1 + ball[0].offsetHeight / 2, 800, 0);
ctx.strokeStyle = 'red';
ctx.stroke();
//绘制下面的切线
ctx.beginPath();
ctx.moveTo(0, 800);
ctx.lineTo(x0 + ball[0].offsetWidth / 2, y0 + ball[0].offsetHeight / 2);
ctx.strokeStyle = '#007AFF';
ctx.stroke();
//绘制上面切线
ctx.beginPath();
ctx.moveTo(800, 0);
ctx.lineTo(x1 + ball[0].offsetWidth / 2, y1 + ball[0].offsetHeight / 2);
ctx.strokeStyle = '#007AFF';
ctx.stroke();
//将相应的小球点位
ball[_this].style.left = x + 'px';
ball[_this].style.top = y + 'px';
}
}
document.onmouseup = function() {
document.onmousemove = null; //鼠标松开,清除鼠标移动事件
}
}
</script>
</body>
<html>
贝塞尔曲线
最新推荐文章于 2022-03-15 20:16:46 发布