canvas仿写贝塞尔曲线的示例代码
程序员文章站
2022-06-30 11:25:36
这篇文章主要介绍了canvas仿写贝塞尔曲线的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧... 17-12-29...
天正在等烟雨,而我在等你,啦啦啦,欢迎关注我的简书,今天分享的是原创的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 = " "; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 弱精吃什么好,这么吃你就吃对了
下一篇: 儿童偏食,千万不要小觑