canvas Picture Trial

Keywords: Java JQuery Javascript less

In these days, I will study canvas drawing again, and simply write a page, which is used to frame items. For the time being, I just want to draw quadrilateral.

  • Just go directly to the code, the comments are written more complete already.

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
            .father {
                position: relative;
                -moz-user-select: none;
                margin-left: 8%;
                margin-top: 3%;
            }
    
            .canvas {
                position: absolute;
                z-index: 1;
            }
    
            .canvas_bgp {
                position: absolute;
            }
        </style>
    </head>
    <body>
    <div class="father" onselectstart="return false;">
        <canvas id="canvas" class="canvas" width="800" height="500">Current browsers do not support canvas,Please change the browser to use!</canvas>
        <img src="./timg.jpg" class="canvas_bgp" width="800" height="500">
    </div>
    </body>
    </html>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script type="text/javascript">
        let canvas = document.getElementById("canvas"); //Get the canvas element
        let context = canvas.getContext("2d"); //Getting Context Environment
        let arrOld = []; //Record historical locations, when retreating
        let timeId; //Remove the impact of the second click
        let arr = []; //Location information of the drawing
    
        // Draw points
        function drawPoint(cxt, x, y, w, borderWidth, borderColor, fillColor) {
            cxt.beginPath();
            cxt.moveTo(x - w, y - w);
            cxt.lineTo(x + w, y - w);
            cxt.lineTo(x + w, y + w);
            cxt.lineTo(x - w, y + w);
            cxt.lineWidth = borderWidth;
            cxt.strokeStyle = borderColor;
            cxt.fillStyle = fillColor;
            cxt.closePath();
            cxt.fill();
            cxt.stroke();
        }
    
        // Polygon
        function drawPolygon(cxt, dbl, borderWidth, borderColor, fillColor, t) {
            for (let i = 0; i < dbl.length; i++) {
                drawPoint(cxt, dbl[i].x, dbl[i].y, 2, 1, 'black', 'skyblue');
            }
            cxt.moveTo(dbl[0].x, dbl[0].y);
            for (let i = 1; i < dbl.length; i++) {
                cxt.lineTo(dbl[i].x, dbl[i].y);
            }
            if (t) {
                cxt.closePath();
                cxt.fillStyle = fillColor;
                cxt.fill();
            }
            cxt.lineWidth = borderWidth;
            cxt.strokeStyle = borderColor;
            cxt.stroke();
        }
    
        // canvas.ondblclick = function () {
        function generate() {
            // clearTimeout(timeId); //Clear the second click event
            // You need to draw more than three points to close.
            if (arr.length > 2) {
                // Add a starting point again so that when you go back, you don't have to disappear two lines at once.
                arr.push({x: arr[0].x, y: arr[0].y});
                drawPolygon(context, arr, 3, 'green', "rgba(0, 0, 0, 0)", false);
                // Save arr
                arrOld.push(arr);
                // Add a message to the list
                addition(arr);
                // After the closure is completed, the coordinate array is cleared for new construction.
                arr = [];
                // Here you need to get the coordinates of all points
                console.log(arrOld);
            } else {
                alert("Unclosed Graphics")
            }
        }
    
        //Click on the location of the determination point
        canvas.onclick = function (e) {
            clearTimeout(timeId);//Clear the second click event
            timeId = setTimeout(function () {
                let x = e.offsetX;
                let y = e.offsetY;
                arr.push({x: x, y: y});
                drawPolygon(context, arr, 3, 'green');
                // Now click on four points to close the graph, because only a quadrilateral is required.
                if(arr.length == 4){
                    generate();
                }
            }, 250)
        };
    
        //fallback action
        canvas.ondblclick = function () {
            clearTimeout(timeId);//Clear the second click event
        // function regression() {
            if(arr.length == 0 && arrOld.length == 0){
                alert("Unable to retreat");
                return;
            }
            if (arr.length > 0) {
                // Delete the drawing
                arr = arr.slice(0, arr.length - 1);
            } else {
                // Delete already drawn
                if (arrOld.length > 0) {
                    // Take out the last one in the history array
                    arr = arrOld[arrOld.length - 1].slice(0, arr.length - 1);
                    // Delete the last one in history
                    arrOld = arrOld.slice(0, arrOld.length - 1);
                }
            }
            //Empty the drawing board and redraw it
            clean();
        };
    
        //Display lines
        canvas.onmousemove = function() {
            //Empty the drawing board and redraw it
            clean();
            //Scribing without dotting
            if(arr.length > 0 && arr.length < 4){
                let bbox = canvas.getBoundingClientRect();
                let x =  event.clientX - bbox.left * (canvas.width/bbox.width);
                let y = event.clientY - bbox.top * (canvas.height/bbox.height);
                context.moveTo(arr[arr.length-1].x, arr[arr.length-1].y);
                context.lineTo(x, y);
                context.lineWidth = 3;
                context.strokeStyle = 'green';
                context.stroke();
            }
        };
    
        // Empty the drawing board and redraw it
        function clean() {
            //Empty the drawing board and redraw it
            context.clearRect(0, 0, 800, 500);
            for (let i = 0; i < arrOld.length; i++) {
                drawPolygon(context, arrOld[i], 3, 'green', "rgba(0, 0, 0, 0)", false);
            }
            if (arr.length > 0) {
                drawPolygon(context, arr, 3, 'green');
            }
        }
    </script>
    
  • The idea is that canvas is redrawn after repeated removal, because it is dotted lines, so I coincidentally saved an additional starting point when the final graphics are completed, so that in the back operation there will be no problem of removing one point and thus two lines less.

Posted by Soogn on Tue, 30 Jul 2019 22:06:08 -0700