<!DOCTYPE html> <html> <style type="text/css"> body{text-align: center;} #can{ border:1px solid black;} </style> <body> <h2>beisaier</h2> <canvas id="can" width="400" height="300" ></canvas> </body> <script> var a=can.getContext("2d"); var b=can.width,c=can.height; var p=function(x,y){ this.x=x; this.y=y; } var v=[]; function ccp(x,y) { if(v.length<4) { v.push(new p(x,y)); } } function dp()//绘制控制点 { for(var i=0;i< v.length;i++) { var e="red"; if(i<2) { e="green"; } a.strokeStyle=e; a.strokeRect(v[i].x-5,v[i].y-5,10,10); } } function is(p1,p2,w,h)//判断一个点是否在以p2为中心的矩形中 { return p1.x>=p2.x-w&&p1.x<p2.x+w&&p1.y>p2.y-h&&p1.y<=p2.y+h; } function getid(pp)判断一个点在哪一个控制区域中 { var id=-1; for(var i=0;i< v.length;i++) { if(is(pp,v[i],10,10)) { return i; } } return id; } function db() { a.strokeStyle="gray"; a.beginPath(); a.moveTo(v[0].x,v[0].y); a.lineTo(v[2].x,v[2].y); a.stroke(); a.moveTo(v[1].x,v[1].y); a.lineTo(v[3].x,v[3].y); a.stroke(); } function dbe() { a.beginPath(); a.strokeStyle="red"; a.moveTo(v[0].x,v[0].y); a.bezierCurveTo(v[2].x,v[2].y,v[3].x,v[3].y,v[1].x,v[1].y); a.stroke(); } function d() { dp(); if(v.length>3) { db(); dbe(); } } var sb=new p(-1,-1),sid; can.onmousedown=function(ee){//鼠标功能设置 var x= ee.offsetX,y= ee.offsetY; sb.x=x;sb.y=y; ccp(x,y); d(); if(v.length>3) { sid=getid(sb); if(sid>=0) { can.onmousemove=function(ee){ v[sid].x= ee.offsetX; v[sid].y= ee.offsetY; a.clearRect(0,0,400,300); d(); } } } } can.onmouseup=function(){//必要的取消鼠标move的设置 this.onmousemove=null; } </script> </html>