您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關canvas如何仿寫貝塞爾曲線的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
效果圖:
html
<canvas id="mycanvas" width="500" height="500">您的瀏覽器不支持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(){ //畫半透明的線 context.beginPath(); context.moveTo(500,0); context.lineTo(0,500); context.strokeStyle = "rgba(0,0,0,0.3)"; context.lineWidth = 10; context.stroke(); //畫連接線 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(); //畫紅球 context.beginPath(); context.arc(x1,y1,10,0,Math.PI*2); context.fillStyle = "orange"; context.fill(); //畫藍球 context.beginPath(); context.arc(x2,y2,10,0,Math.PI*2); context.fillStyle = "blue"; context.fill(); //畫貝塞爾曲線 context.beginPath(); context.moveTo(0,500); context.bezierCurveTo(x1,y1,x2,y2,500,0); context.lineWidth = 5; context.stroke(); } //拖動小球做動畫 //判斷是否拖動小球 //如果在小球上就做動畫 canvas.onmousedown = function(e){ var ev = e || window.event; var x = ev.offsetX; var y = ev.offsetY; //判斷是否在紅球上 var dis = Math.pow((x-x1),2) + Math.pow((y-y1),2); if(dis<100){ console.log("鼠標在紅球上"); canvas.onmousemove = function(e){ var ev = e || window.event; var xx = ev.offsetX; var yy = ev.offsetY; //清除畫布 context.clearRect(0,0,canvas.width,canvas.height); x1 = xx; y1 = yy; //重繪制 draw(); } } //判斷鼠標是否在藍球上 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; //清除畫布 context.clearRect(0,0,canvas.width,canvas.height); x2 = xx1; y2 = yy1; //重繪制 draw(); } } } document.onmouseup =function(){ canvas.onmousemove = " "; }
感謝各位的閱讀!關于“canvas如何仿寫貝塞爾曲線”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。