The sky is waiting for misty rain, and I am waiting for you, la la la, welcome to follow my short book. What I am sharing today is the original method of imitating Bezier curves on canvas. The details are as follows:
Rendering:
html
<canvas id=mycanvas width=500 height=500>Your browser does not support canvas</canvas>
css
canvas{ border: 1px solid black;}
js
var canvas = document.getElementById(mycanvas); var context = canvas.getContext(2d); var x1 = 100; var y1 = 100; var x2 = 400; var y2 = 400; draw(); function draw(){ / /Draw a semi-transparent line context.beginPath(); context.moveTo(500,0); context.lineTo(0,500); context.strokeStyle = rgba(0,0,0,0.3); context.lineWidth = 10; context.stroke(); //Draw a connecting line context.beginPath(); context.moveTo(0,500 ); context.lineTo(x1,y1); context.lineWidth = 2; context.strokeStyle = black; context.stroke(); context.beginPath(); context.moveTo(500,0); context.lineTo(x2,y2); context.lineWidth = 2; context.strokeStyle = black; context.stroke(); //Draw a red ball context.beginPath (); context.arc(x1,y1,10,0,Math.PI*2); context.fillStyle = orange; context.fill(); //Draw a blue ball context.beginPath(); context.arc(x2,y2,10,0,Math.PI*2); context.fillStyle = blue; context.fill(); //Draw a Bezier curve context .beginPath(); context.moveTo(0,500); context.bezierCurveTo(x1,y1,x2,y2,500,0); context.lineWidth = 5; context.stroke(); } //Drag the ball to animate//Determine whether to drag the ball//If it is on the ball, animate canvas.onmousedown = function(e){ var ev = e || window.event; var x = ev.offsetX; var y = ev.offsetY; //Determine whether it is on the red ball var dis = Math.pow((x-x1),2) + Math.pow((y-y1),2); if(dis<100){ console.log(mouse is on the red ball); canvas.onmousemove = function(e){ var ev = e || window.event; var xx = ev.offsetX; var yy = ev.offsetY; //Clear the canvas context.clearRect(0,0,canvas.width,canvas.height); x1 = xx; y1 = yy; //Redraw draw(); } } //Determine whether the mouse is on the blue ball var dis = Math.pow((x-x2),2) + Math.pow((y-y2) ,2); if(dis<100){ canvas.onmousemove = function(e){ var ev = e || window.event; var xx1 = ev.offsetX; var yy1 = ev.offsetY; //Clear the canvas context.clearRect(0,0,canvas.width,canvas.height); x2 = xx1; y2 = yy1; //Redraw draw(); } } } document.onmouseup =function( ){ canvas.onmousemove = ; }
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.