canva博大精深,小女子不才,只会一点基础用法(圆,矩形)。😓感叹自己好渣。此处对canvas基本用法不赘述,有机会整理一下canvas和svg基础和同异。其实画心,画玫瑰等,知道了方程式,可以确定每一步绘制的点,接下来就好办了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用桃心形方程绘制爱心</title>
<style>
body,p{ margin: 0;padding: 0; }
p{ position: absolute;top: 0;left: 0;width: 200px; height: 300px; /* background: rgba(234, 234,211, 0.3) */ }
</style>
</head>
<body>
<canvas id='heart'></canvas>
<p></p>
<div>桃心型线的参数方程:x = 16 (sinθ)^3 y = 13 cosθ- 5 cos 2θ - 2 cos 3θ - cos 4θ </div>
<script>
let az = document.getElementById('heart');
let cont = az.getContext('2d');
az.width = 400;
az.height = 400;
let get_arr = function(a,len){
let arr=[];
for(let i=0;i<len;i++){
let step = i/len*(Math.PI*2);//递增的θ
let vector = {
x : a*(16 * Math.pow(Math.sin(step), 3)),
y : -a*(13 * Math.cos(step) - 5 * Math.cos(2 * step) - 2 * Math.cos(3 * step) - Math.cos(4 * step))
}
arr.push(vector);
}
return arr;
}
function draw_heart(){
cont.beginPath();
cont.translate(100,100);//设置偏移让心形显示完整
cont.strokeStyle = 'red';
cont.lineWidth = 1;
let len = 50;
let arr = get_arr(4,50)//获取心形所有点的数据 心形放大4倍
console.log(arr);
for(let i=0;i<len;i++){
cont.lineTo(arr[i].x,arr[i].y);//心形的点一一被描绘出来
}
cont.stroke();
}
draw_heart();
</script>
</body>
</html>