js+canvas Realization of Sketchpad Function

  • 2021-08-21 19:29:15
  • OfStack

In this paper, we share the specific code of js + canvas to realize the drawing board function for your reference. The specific contents are as follows

1. The functions of drawing, changing brush thickness, changing brush color and clearing screen are realized


<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8" />
 <title> Drawing board </title>
 <link rel="shortcut icon" type="image/x-icon" href="img/an.ico" />
 <link rel="stylesheet" type="text/css" href="css/drow.css" />
 </head>
 <body>
 <canvas id="mycanvas" width="1100px" height="660px"></canvas>
 <div class="tool">
   Brush color :<input type="color" name="color1" id="color1"/><br />
   Brush thickness :<input type="range" name="range1" id="range1"min="1" max="20"/><br />
  <button class="btn"> Clear screen </button>
 </div>
 </body>
 <script src="js/drow.js" type="text/javascript" charset="utf-8"></script>
</html>

*{
 margin: 0;
 padding: 0;
 text-align: left;
 -moz-user-select: none;
 -ms-user-select: none;
 -webkit-user-select: none;
}
#mycanvas{
 border: 2px solid deepskyblue;
}
.tool{
 width: 260px;
 height: 100%;
 position: fixed;
 right: 0;
 top: 0;
 background-color: #CCCCCC;
}

// Get an object 
var mycanvas = document.getElementById("mycanvas");
var color1 = document.getElementById("color1");
var range1 = document.getElementById("range1");
var btn = document.getElementsByClassName("btn")[0];
var contxt = mycanvas.getContext("2d");
btn.onclick=function () {
 contxt.clearRect(0,0,1200,660);
}
var flag = false;
var x = 0,
 y = 0;
//  Mouse click event 
mycanvas.onmousedown = function(event) {
 flag = true;
 //  Gets the starting position under the mouse click 
 var x = event.clientX - mycanvas.offsetLeft;
 var y = event.clientY - mycanvas.offsetTop;
 contxt.beginPath(); //  Start creating a new path 
 contxt.strokeStyle = color1.value; //  Get color assignment to brush 
 contxt.lineCap="round";
 contxt.lineWidth = range1.value; //  Get the brush width and assign it to the brush 
 contxt.moveTo(x, y); //  Start position 
 }
//  Mouse movement event 
mycanvas.onmousemove = function(event) {
 //  Gets where the mouse is moving 
 var mX = event.clientX - mycanvas.offsetLeft;
 var mY = event.clientY - mycanvas.offsetTop;
 if (flag) {
  contxt.lineTo(mX, mY); //  Move in and out of position 
  contxt.stroke(); //  End rendering canvas 
 }
 }
//  Mouse release event 
mycanvas.onmouseup = function() {
 flag = false;
}

Related articles: