在js中绘制多个多边形

时间:2016-01-18 11:02:24

标签: javascript canvas polygon

我正在使用这段代码,它与魅力一起工作 - 它在给定的图片上绘制一个多边形(带有画布),但是我努力修改代码,这样它就能让我画出来多个多边形而不是一个多边形。 我是一个nos to 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>

1 个答案:

答案 0 :(得分:4)

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

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

工作示例:

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