代碼實現的一種方法html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>使用桃心形方程繪製愛心</title> </head> <body> <canvas></canvas> <script> var canvas = document.querySelector('canvas'); var ctx = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var Heart = function(ctx, x, y, a) { this.ctx = ctx; this.x = x; this.y = y; this.a = a; this.vertices = []; for(let i=0; i<50; i++) { var step = i/50*(Math.PI*2);//設置心上面兩點之間的角度,具體分紅多少份,好像須要去試。 var vector = { x : this.a*(16 * Math.pow(Math.sin(step), 3)), y : this.a*(13 * Math.cos(step) - 5 * Math.cos(2 * step) - 2 * Math.cos(3 * step) - Math.cos(4 * step)) } this.vertices.push(vector); } } Heart.prototype.draw = function() { this.ctx.beginPath(); this.ctx.translate(this.x,this.y); this.ctx.rotate(Math.PI); for(let i=0; i<50; i++) { var vector = this.vertices[i]; this.ctx.lineTo(vector.x, vector.y); } this.ctx.fillStyle = "red"; this.ctx.fill(); } canvas.onmousedown = function(e) { var x = e.offsetX; var y = e.offsetY; var a = 6; var heart = new Heart(ctx, x, y, a); heart.draw(); } </script> </body> </html>
代碼實現的一種方法:canvas
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>使用笛卡爾心形線方程繪製愛心</title> </head> <body> <canvas></canvas> <script> var canvas = document.querySelector('canvas'); var ctx = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; function Heart(ctx, x, y, a) { this.ctx = ctx; this.x = x; this.y = y; this.a = a; this.draw = function() { this.ctx.beginPath(); this.ctx.translate(this.x, this.y); this.ctx.rotate(Math.PI); var start = 0; for(var i=0; i<500; i++) { start += Math.PI*2/500; var end = start+Math.PI*2/500; var r = this.a*(1-Math.sin(start)); ctx.arc(0, 0, r, start, end, false); } ctx.fillStyle = "red"; ctx.fill(); } } canvas.onmousedown = function(e) { var x = e.offsetX; var y = e.offsetY; var a = 60; var heart = new Heart(ctx, x, y, a); heart.draw(); } </script> </body> </html>