简体   繁体   English

在JS中绘制多个多边形

[英]Drawing multiple polygons in js

I'm using this code, and it works with charm - It draws a polygon (with canvas) on a given picture, however I'm struggling to modify code, so that it would enable me to draw multiple polygons instead of just one. 我正在使用此代码,并且具有一定的魅力-它在给定的图片上绘制了一个多边形(带有画布),但是我正在努力修改代码,以便使我能够绘制多个多边形而不是一个多边形。 I'm a noob to js and haven't found yet anything that might solve it, I'd appreciate any help/hint in some direction. 我对js不熟悉,还没有找到任何可能解决该问题的方法,希望能对您有所帮助。

Code: 码:

    <!DOCTYPE html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="main.css">
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.js"></script>
    <script>

    //radius of click around the first point to close the draw
    var END_CLICK_RADIUS = 15;
    //the max number of points of your polygon
    var MAX_POINTS = 8;

    var mouseX = 0;
    var mouseY = 0;
    var isStarted = false;
    var points = null;

    var canvas = null;



    window.onload = function() {
        background = document.getElementById('justanimage');

        //initializing canvas and draw color
        canvas = document.getElementById("canvas");
        ctx = canvas.getContext("2d");
        changeColor("blue");

        image = new Image();
        image.onload = function() {
            ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
        };
        image.src = 'justanimage.gif';


        canvas.addEventListener("click", function(e) {
            var x = e.clientX-canvas.offsetLeft;
            var y = e.clientY-canvas.offsetTop;
            if(isStarted) {
                //drawing the next line, and closing the polygon if needed
                if(Math.abs(x - points[0].x) < END_CLICK_RADIUS && Math.abs(y - points[0].y) < END_CLICK_RADIUS) {
                    isStarted = false;
                } else {
                    points[points.length] = new Point(x, y);
                    if(points.length >= MAX_POINTS) {
                        isStarted = false;
                    }
                }
            } else if(points == null) {
                //opening the polygon
                points = new Array();
                points[0] = new Point(x, y);
                isStarted = true;
            }
        }, false);

        //we just save the location of the mouse
        canvas.addEventListener("mousemove", function(e) {
            mouseX = e.clientX - canvas.offsetLeft;
            mouseY = e.clientY - canvas.offsetTop;
        }, false);

        //refresh time
        setInterval("draw();", 5);

    }

    //object representing a point
    function Point(x, y) {
        this.x = x;
        this.y = y;
    }

    //resets the application
    function reset() {
        isStarted = false;
        points = null;
        document.getElementById("coordinates").innerHTML = " ";
    }

    //displays coordinates of the the point list
    function save() {
        if(points == null) {
            alert("No picture!");
        } else {
            var s = "";
            for(var a in points) {
                //inversing y axis by (canvas.height - points[a].y)
                s += "(" + points[a].x + "," + (canvas.height - points[a].y) + ")\n";
            }
            document.getElementById("coordinates").innerHTML = s + '\n';
        }
    }

    //draws the current shape
    function draw() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        ctx.beginPath();

        if(points != null && points.length > 0) {
            ctx.moveTo(points[0].x, points[0].y);

            for(i = 1 ; i < points.length ; i++) {
                ctx.lineTo(points[i].x, points[i].y);
            }

            if(isStarted) {
                ctx.lineTo(mouseX, mouseY);
            } else {
                ctx.lineTo(points[0].x, points[0].y);
            }
        }
        ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
        ctx.stroke();
    }


</script>


    </head>
    <body>
    <div id="outer">
    <canvas id="canvas" width=300 height=300; ></canvas>
    </div>

    <p id="coordinates"> </p>
    <input type="button" value="Save" onclick="save();" />
    <input type="button" value="Reset" onclick="reset();" />

    </body>
    </html>

Basically this solution adds a new array polygons , which keeps all polygons. 基本上,此解决方案会添加一个新的polygons数组,该数组将保留所有多边形。 The points array is now included in the polygons . 现在, points组已包含在polygons

var polygons = [];

window.onload = function () {
    // ...
    canvas.addEventListener("click", function (e) {
        // ...
        if (isStarted) {
            //drawing the next line, and closing the polygon if needed
            if (Math.abs(x - polygons[polygons.length - 1][0].x) < END_CLICK_RADIUS && Math.abs(y - polygons[polygons.length - 1][0].y) < END_CLICK_RADIUS) {
                isStarted = false;
            } else {
                polygons[polygons.length - 1].push(new Point(x, y));
                if (polygons[polygons.length - 1].length >= MAX_POINTS) {
                    isStarted = false;
                }
            }
        } else {
            //opening the polygon
            polygons.push([new Point(x, y)]);
            isStarted = true;
        }
    }, false);
    // ...
}


function draw() {
    ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
    polygons.forEach(function (points, i) {
        ctx.beginPath();
        points.forEach(function (p, j) {
            if (j) {
                ctx.lineTo(p.x, p.y);
            } else {
                ctx.moveTo(p.x, p.y);
            }
        });
        if (i + 1 === polygons.length && isStarted) { // just the last one
            ctx.lineTo(mouseX, mouseY);
        } else {
            ctx.lineTo(points[0].x, points[0].y);
        }
        ctx.stroke();
    });
}

(Another solution might be to save the image with the last polygon and use it again for the new polygon.) (另一种解决方案可能是保存带有最后一个多边形的图像,然后将其再次用于新的多边形。)

Working example: 工作示例:

 //radius of click around the first point to close the draw var END_CLICK_RADIUS = 15; //the max number of points of your polygon var MAX_POINTS = 8; var mouseX = 0; var mouseY = 0; var isStarted = false; var polygons = []; var canvas = null; var ctx; var image; window.onload = function () { var background = document.getElementById('justanimage'); //initializing canvas and draw color canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); //changeColor("blue"); // <-- is missing! image = new Image(); image.onload = function () { ctx.drawImage(image, 0, 0, canvas.width, canvas.height); }; image.src = 'http://lorempixel.com/10/10/'; canvas.addEventListener("click", function (e) { var x = e.clientX - canvas.offsetLeft; var y = e.clientY - canvas.offsetTop; if (isStarted) { //drawing the next line, and closing the polygon if needed if (Math.abs(x - polygons[polygons.length - 1][0].x) < END_CLICK_RADIUS && Math.abs(y - polygons[polygons.length - 1][0].y) < END_CLICK_RADIUS) { isStarted = false; } else { polygons[polygons.length - 1].push(new Point(x, y)); if (polygons[polygons.length - 1].length >= MAX_POINTS) { isStarted = false; } } } else { //opening the polygon polygons.push([new Point(x, y)]); isStarted = true; } }, false); //we just save the location of the mouse canvas.addEventListener("mousemove", function (e) { mouseX = e.clientX - canvas.offsetLeft; mouseY = e.clientY - canvas.offsetTop; }, false); //refresh time setInterval("draw();", 5); } //object representing a point function Point(x, y) { this.x = x; this.y = y; } //resets the application function reset() { isStarted = false; points = null; document.getElementById("coordinates").innerHTML = " "; } //draws the current shape function draw() { ctx.drawImage(image, 0, 0, canvas.width, canvas.height); polygons.forEach(function (points, i) { ctx.beginPath(); points.forEach(function (p, j) { if (j) { ctx.lineTo(px, py); } else { ctx.moveTo(px, py); } }); if (i + 1 === polygons.length && isStarted) { // just the last one ctx.lineTo(mouseX, mouseY); } else { ctx.lineTo(points[0].x, points[0].y); } ctx.stroke(); }); } 
 <canvas id="canvas" width="500" height="500"></canvas> <img id="justanimage" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM