Home > Article > Web Front-end > Draw a gradient circle diagonal with JavaScript
In the previous article "Fun Implementation of JS: Give You a Smiling Face with Glasses", I introduced you how to use js to draw a smiling face with glasses. It's quite fun ~ those who are interested Friends can take a look, haha~ Then this article will continue to introduce you to an interesting drawing method.
The theme of today's article is "Write a JavaScript program to draw the following figure [diagonal line, white to black circle]."
Maybe you don’t know what you want to achieve when you first read the title, but now this picture should be very clear and understandable! You can try how to use js to achieve this rendering locally.
The following is my implementation method:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <canvas id="myCanvas" width="1500" height="800"> <p>更新您的浏览器!</p> </canvas> <script> function draw() { var ctx = document.getElementById("myCanvas").getContext("2d"); var counter = 0; for (var i=0;i<6;i++) { for (var j=0;j<6;j++) { //从白到黑 ctx.fillStyle = "rgb(" + Math.floor(255-42.5*i) + "," + Math.floor(255-42.5*i) + "," + Math.floor(255-42.5*j) + ")"; ctx.beginPath(); if (i === counter && j === counter) { //创建圈 ctx.arc(25+j*50,30+i*50,20,0,Math.PI*2,true); ctx.fill(); //在圆圈周围创建一个边框,这样白色的会可见 ctx.stroke(); } } counter++; } } draw(); </script> </body> </html>
Okay, let’s run this code directly. The effect is as follows:
Simple Introducing the methods involved:
getElementById() method: can return a reference to the first object with the specified ID;
getContext() method: returns an object for displaying on the canvas Drawing environment;
floor() method: can round down a number;
fill() method: fill the current image (path), the default color is black;
fillStyle property: Set or return the color, gradient or pattern used to fill the painting;
beginPath() method: start a path, or reset the current path;
arc () method: creates an arc/curve (used to create a circle or partial circle);
stroke() method: will actually draw the path defined by the moveTo() and lineTo() methods. The default color is black.
Finally, I would like to recommend "JavaScript Basics Tutorial" ~ Welcome everyone to learn ~
The above is the detailed content of Draw a gradient circle diagonal with JavaScript. For more information, please follow other related articles on the PHP Chinese website!