Recently, I have studied some new element attributes of HTML5 and found that they are really easy to use, especially the new tag element Canvas. Official introduction: Canvas API (canvas) is a new tag in HTML5 that is used to generate images in real time on web pages and can manipulate image content. Basically, it is a bitmap that can be manipulated with JavaScript. The following uses JavaScript combined with Canvas to implement a drawing board function
Effect demonstration picture:
Code part (copy it directly and use it)
<!DOCTYPE HTML><html><head> <meta charset=utf-8 /> <title>JavaScript+Canvas implements custom drawing board</title></head><body><canvas id=canvas width=600 height =300></canvas><script type=text/javascript> var canvas = document.getElementById(canvas); var ctx = canvas.getContext(2d); //Draw a black rectangle ctx.fillStyle=black; ctx.fillRect(0,0,600,300); //Press the mark var onoff = false; //The variables oldx and oldy represent the coordinates before the mouse moves var oldx = -10; var oldy = -10; //Set the color var linecolor = white; //Set the line width var linw = 4; //Add mouse move event canvas.addEventListener(mousemove,draw,true); //The third parameter is mainly related to capturing or bubbling //Add mouse press event canvas.addEventListener(mousedown,down,false); // Add mouse up event canvas.addEventListener(mouseup,up,false); function down(event){ onoff = true; oldx = event.pageX-10; oldy = event.pageY-10; //console.log(event.pageX+'............000.............'+event.pageY) ; //event.pageX and event.pageY are relative to the mouse position of the entire page including the overflow part (that is, the scroll bar) } function up(){ onoff = false; } function draw(event){ if(onoff == true) { var newx = event.pageX-10; var newy = event.pageY-10; ctx.beginPath();//beginPath() Discards any currently defined path and starts a new one. It sets the current point to (0,0). ctx.moveTo(oldx,oldy); //Move to the coordinate when clicked, with that coordinate as the origin ctx.lineTo(newx,newy); //Draw a new path ctx.strokeStyle=linecolor; ctx.lineWidth=linw; ctx.lineCap=round; ctx.stroke();//The stroke() method will actually draw the path defined by the moveTo() and lineTo() methods. The default color is black. //Assign the new mouse position to the starting coordinate of the next drawing start oldx = newx; oldy = newy; }; };</script></body></html>The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.