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; var Heart = function(x, y) { this.x = x; this.y = y; this.vertices = []; for(let i=0; i<30; i++) { var step = i / 30 * (Math.PI * 2);//设置心上面两点之间的角度,具体分成多少份,好像需要去试。 var vector = { x : (15 * Math.pow(Math.sin(step), 3)), y : -(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() { ctx.translate(-1000,this.y);//这一步跟ctx.shadowOffsetX必须一起使用,不明白为啥? ctx.beginPath(); for(let i=0; i<30; i++) { var vector = this.vertices[i]; ctx.lineTo(vector.x, vector.y); } ctx.shadowColor = "red"; ctx.shadowOffsetX = this.x+1000; ctx.fill(); } canvas.onmousedown = function(e) { var x = e.offsetX; var y = e.offsetY; var heart = new Heart(x, y); heart.draw(); } </script> </body> </html>
代码里面有两处地方不明白 ctx.translate(-1000,this.y); 跟 ctx.shadowOffsetX = this.x+1000; 能感觉出来什么意思,但是不知道为啥要加上,去掉就不行了。请路过的各位大佬们帮忙解答一下~~
相关推荐
大地飞鸿 2020-11-12
星星有所不知 2020-10-12
jinxiutong 2020-07-26
MIKUScallion 2020-07-05
songfens 2020-07-05
songfens 2020-06-11
songfens 2020-06-08
northwindx 2020-05-31
northwindx 2020-05-31
northwindx 2020-05-27
northwindx 2020-05-25
MIKUScallion 2020-05-25
jinxiutong 2020-05-10
xdyangxiaoromg 2020-05-10
大地飞鸿 2020-05-06
northwindx 2020-04-25