Dessiner des polygones avec la souris

Contenu du snippet

Ce code vous permettra de tracer des polygones très simplement avec votre souris.

Je pense l'avoir fait assez simple pour qu'il soit facilement adaptable à vos besoins.

Il est également possible de les sauvegarder avec la fonction save (qu'il faudra adapter à vos besoins, elle ne fait qu'afficher la liste des points).

J'ai également mis un nombre maximum de points car j'en ai besoin pour mon application, mais c'est facilement adaptable.

Source / Exemple :


<html>
	<head>
		<script type="text/javascript">
			/*

  • JavaScript polygon drawing
  • Sébastien CAPARROS
  • /
//radius of click around the first point to close the draw var END_CLICK_RADIUS = 5; //the max number of points of your poygon var MAX_POINTS = 8; var mouseX = 0; var mouseY = 0; var isStarted = false; var points = null; var canvas = null; var ctx = null; window.onload = function() { //initializing canvas and draw color canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); changeColor("red"); 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();", 100); } //changes the color of the draw function changeColor(color) { ctx.strokeStyle = color; } //object representing a point function Point(x, y) { this.x = x; this.y = y; } //resets the application function reset() { isStarted = false; points = null; } //alerts the point list function save() { if(points == null) { alert("Rien a sauvegarder !"); } 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"; } alert(s); } } //draws the current chape 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.stroke(); } </script> </head> <body> <canvas id="canvas" width="300" height="300" style="border: 1px solid black;"></canvas> <br /><br /> <input type="button" value="Sauvegarder" onclick="save();" />&nbsp; <input type="button" value="Effacer" onclick="reset(); " />&nbsp; Couleur : <select id="color" onchange="changeColor(this.options[this.selectedIndex].value);"> <option value="red" selected="selected">Rouge</option> <option value="blue" selected="selected">Bleu</option> <option value="green" selected="selected">Vert</option> <option value="black" selected="selected">Noir</option> <option value="yellow" selected="selected">Jaune</option> </select> </body> </html>

Conclusion :


J'ai cherché un code tout fait pendant pas mal de temps, mais je n'ai rien trouvé. Ce n'est finalement pas bien compliqué d'ailleurs.

Je me suis donc lancé, et voilà le résultat.

Ce code ne fonctionnera sous internet explorer que si vous incluez une librairie du type excanvas.

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.