四叶草的效果:

Canvas实现多叶草效果的封装_2d


想要实现四叶草以及多叶草的效果,需要了解四叶草的构成。

想要在网页上作图,则需要添加画布Canvas,而四叶草是由曲线构成的,可以使用贝塞尔曲线来绘制,

HTML代码:

<canvas id="canvas" width="200" height="150"></canvas>

JS代码:

  function $(id){
return document.getElementById(id);
}
window.onload = function(){
var canvas = $("canvas");
var ctx = canvas.getContext("2d");
createLeaf(ctx,4,canvas.width/2,canvas.height/2,30,80);
ctx.fillStyle = "#13EE8E";
ctx.fill();
}

//封装绘制四叶草的函数
function createLeaf(ctx,n,dx,dy,size,length){
ctx.beginPath();
ctx.moveTo(dx,dy+size);
var degree = 2 * Math.PI / n;
for(var i=1;i<n+1;i++){

//计算控制点的坐标
var cx1 = Math.sin((i-1)*degree)*length + dx;
var cy1 = Math.cos((i-1)*degree)*length + dy;
var cx2 = Math.sin(i*degree)*length + dx;
var cy2 = Math.cos(i*degree)*length + dy;

//计算终点的坐标
var x = Math.sin(i*degree)*size+dx;
var y = Math.cos(i*degree)*size+dy;
ctx.bezierCurveTo(cx1,cy1,cx2,cy2,x,y);
}
ctx.closePath();
}