Home > Web Front-end > JS Tutorial > body text

Draw hearts on the WEB

php中世界最好的语言
Release: 2017-12-30 17:58:18
Original
3307 people have browsed it

What I bring to you this time is how to draw hearts on the WEB. Without further ado, I will directly present a case for you to analyze.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>使用桃心形方程绘制爱心</title>
</head>
<body>
 <canvas></canvas>
 <script>
 var canvas = document.querySelector(&#39;canvas&#39;);
 var ctx = canvas.getContext(&#39;2d&#39;);
 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>
Copy after login

I believe you have mastered the method after reading the above introduction. For more exciting information, please pay attention to php Chinese website Other related articles!

Related reading:

Answers to questions about camel case naming and JS

Boolean values, relational operators in JS, Detailed explanation and examples of logical operators

How to customize the console object when using JS

The above is the detailed content of Draw hearts on the WEB. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!