mardi 30 septembre 2014

Make JavaScript event handler depend on AJAX response


Vote count:

0




A JavaScript beginner here :) I am trying to write a Web photo viewer where faces would be marked on the photos. To switch between photos, I'd like to use AJAX. My PHP script returns the name of the picture file and the coordinates of faces (x, y, radius) in the form of a JSON string, e.g.



{"filename":"im1.jpg","faces":[{"x":129,"y":260,"radius":40},{"x":232,"y":297,"radius":40}]}


I want to draw circles on a canvas, based on faces, once the mouse is over the photo. Therefore I created a listener for the mouseover event. The problem is that if I add the listener after the AJAX call, the canvas gets multiple listeners and keeps drawing circles from the previous photos. So it looks like the handler needs to be defined in advance. But then I am struggling to pass the AJAX response to it. How could I achieve it?


My HTML code so far looks like this:



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<canvas id="canvas" width="100" height="600"
style="background-size: 100% 100%; border: 1px solid #FF0000;"></canvas>
<script>
var image = new Image();
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

function loadXMLDoc() {

var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var ajaxData = JSON.parse(xmlhttp.responseText);
image.src = ajaxData.filename;
image.onload = function() {
canvas.width = Math.round(canvas.height / image.height * image.width);
canvas.style.backgroundImage = "url('" + image.src + "')";
}
var faces = ajaxData.faces;
canvas.addEventListener('mouseout', function(evt) {
context.clearRect(0, 0, canvas.width, canvas.height);
console.log("Canvas cleared");
}, false);

canvas.addEventListener('mouseover', function(evt) {
console.log("Canvas entered");
console.log("Faces to mark: " + faces.length);

for (i = 0; i < faces.length; i++) {
context.beginPath();
context.arc(faces[i].x, faces[i].y,
faces[i].radius, 0, 2 * Math.PI);
context.strokeStyle = "#00BBBB";
context.lineWidth = 1;
context.stroke();
}
}, false);

}
}
xmlhttp.open("GET", "get_data.php", true);
xmlhttp.send();
}
</script>

<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>


asked 33 secs ago

texnic

662






Make JavaScript event handler depend on AJAX response

Aucun commentaire:

Enregistrer un commentaire