在 js 中绘制多个多边形

Drawing multiple polygons in js

本文关键字:多边形 绘制 js      更新时间:2023-09-26

我正在使用此代码,它与魅力一起工作 - 它在给定的图片上绘制一个多边形(带画布),但是我正在努力修改代码,以便它使我能够绘制多个多边形而不仅仅是一个多边形。我是js的菜鸟,还没有找到任何可能解决它的东西,我将不胜感激在某些方向上的任何帮助/提示。

法典:

    <!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>

基本上这个解决方案添加了一个新的数组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();
    });
}

(另一种解决方案可能是将图像与最后一个多边形一起保存,然后再次将其用于新多边形。

工作示例:

//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(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();
    });
}
<canvas id="canvas" width="500" height="500"></canvas>
<img id="justanimage" />