JavaScript 中绘制爱心形状需要如下步骤:创建画布元素并获取其上下文对象。设置画布大小。使用贝塞尔曲线绘制爱心形状。填充爱心。绘制爱心边框。

JS绘制爱心
在JavaScript中绘制一个爱心形状,可以使用以下步骤:
1. 创建一个画布元素
<code class="js">const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');</code>2. 设置画布大小
<code class="js">canvas.width = 400; canvas.height = 300;</code>
3. 使用贝塞尔曲线绘制爱心
<code class="js">ctx.beginPath(); ctx.moveTo(200, 100); ctx.bezierCurveTo(250, 100, 300, 150, 200, 200); ctx.bezierCurveTo(100, 150, 50, 100, 200, 100); ctx.closePath();</code>
4. 填充爱心
<code class="js">ctx.fillStyle = 'red'; // 设置填充色 ctx.fill();</code>
5. 绘制边框
<code class="js">ctx.strokeStyle = 'black'; // 设置边框色 ctx.lineWidth = 3; // 设置边框宽度 ctx.stroke();</code>
完整代码:
<code class="js">const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 300;
ctx.beginPath();
ctx.moveTo(200, 100);
ctx.bezierCurveTo(250, 100, 300, 150, 200, 200);
ctx.bezierCurveTo(100, 150, 50, 100, 200, 100);
ctx.closePath();
ctx.fillStyle = 'red';
ctx.fill();
ctx.strokeStyle = 'black';
ctx.lineWidth = 3;
ctx.stroke();
document.body.appendChild(canvas);</code>










