#简言
利用canvas画出心形图案。
心形
心形图案可以两个椭圆相交组合,也可以直接画路径实现。
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>心形</title><style>#canvas {border: 1px solid #000;}#canvas2 {border: 1px solid #000;}</style></style>
</head><body><div><canvas id="canvas" width="500" height="500"></canvas><canvas id="canvas2" width="50" height="50"></canvas></div><script>const canvas = document.getElementById('canvas');const ctx = canvas.getContext('2d');let start = [250, 100]let end = [250, 400]let add = falselet w = 100let redV = 200initCanvas2()function Drawheart(ctx) {if (end[1] > 400) {add = false} else if (end[1] < 375) {add = true}if (add) {end[1] += 1start[1] -= 0.2w += 2} else {end[1] -= 1start[1] += 0.2w -= 2}let pattern = ctx.createPattern(document.getElementById('canvas2'), 'repeat')ctx.clearRect(0, 0, 500, 500);ctx.save();ctx.strokeStyle = pattern;ctx.lineWidth = w;// ctx.lineJoin = "round";ctx.lineCap = "round";ctx.beginPath();ctx.moveTo(start[0], start[1])ctx.bezierCurveTo(0, 0, 75, 325, end[0], end[1]);ctx.moveTo(start[0], start[1])ctx.bezierCurveTo(500, 0, 425, 325, end[0], end[1]);ctx.shadowColor = "red";ctx.shadowOffsetX = 1;ctx.shadowOffsetY = 1;ctx.shadowBlur = 50;ctx.stroke();// ctx.fill()ctx.restore()initCanvas2()window.requestAnimationFrame((t) => {Drawheart(ctx)})}function initCanvas2() {const ctx2 = document.getElementById('canvas2').getContext('2d');ctx2.clearRect(0, 0, 50, 50)ctx2.save()if (add) {redV -= 1ctx2.rotate(0.05 * Math.PI)} else {redV += 1ctx2.rotate(-0.05 * Math.PI)}ctx2.beginPath();ctx2.moveTo(25, 10)ctx2.bezierCurveTo(0, 0, 7.5, 32.5, 25, 40);ctx2.moveTo(25, 10)ctx2.bezierCurveTo(50, 0, 42.5, 32.5, 25, 40);ctx2.fillStyle = `rgba(${redV},0,0,1)`;ctx2.shadowColor = "red";ctx2.shadowOffsetX = 1;ctx2.shadowOffsetY = 1;ctx.shadowBlur = 10;ctx2.fill();ctx2.restore();}window.requestAnimationFrame(() => Drawheart(ctx))</script>
</body></html>
结语
结束了。