In this lesson, we are going to try something more challenging. Previously, when we discussed pointer events, we mentioned that it is possible to access the pointer coordinates using the clientX
and clientY
properties in the event object.
1let button = document.getElementById("button");
2
3button.addEventListener("click", (event) => {
4 console.log("X: " + event.clientX);
5 console.log("Y: " + event.clientY);
6});
Also, recall that you can find out which mouse button is clicked by accessing the button
property.
1button.addEventListener("click", (event) => {
2 if (event.button == 0) {
3 console.log("Left button");
4 } else if (event.button == 1) {
5 console.log("Middle button");
6 } else if (event.button == 2) {
7 console.log("Right button");
8 }
9});
Combining these concepts, you can create a simple drawing board that creates a star when you click on the page using the primary button, and clicking on the star with the secondary button will remove it.
Preparations
1<!doctype html>
2<html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <title>Drawing Board</title>
7 </head>
8
9 <body>
10 <svg id="drawingBoard" width="100%" height="500"></svg>
11
12 <script src="index.js"></script>
13 </body>
14</html>
Let's start with the HTML code. You only need one <svg>
element in this case, and make sure to set its id
to drawingBoard
.
Drawing stars
Next, you need a function that draws the star. The idea is to create <polygon>
elements with different point
attributes and appended as <svg>
's child when the function is executed.