Рисунок многоугольников в JS



Я использую этот код, и он работает с очарованием - он рисует многоугольник (с холстом) на данной картинке, однако я изо всех сил пытаюсь изменить код, чтобы он позволил мне нарисовать несколько полигонов вместо одного.
Я новичок в 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>
578   1  

1 ответ:

В основном это решение добавляет новый массив 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" />

Comments

    Ничего не найдено.