-2

i want it to be able to go the url in the page and get the next url and so on till the drawing is complete

function linkedDrawing(canvas,url){
    fetch(url)
   .then((response)=> response.json())
   .then((data)=>{
       url = data.url;
       alert(data.url);
       const c = canvas.getContext('2d');
       c.beginPath();
       c.moveTo(data.x1, data.y1);
       c.lineTo(data.x2, data.y2);
       c.strokeStyle = data.col;
       c.stroke();
     })
   }
 }
 linkedDrawing(linkedDrawingCanvas, "http://jacek.soc.port.ac.uk/tmp/ws/alpha.json")

my fiddle: http://jsfiddle.net/g1nqkn7h/3/

codingmonk
  • 33
  • 3
  • You're not providing enough context. What's in the response data? I assume there can be a URL somewhere? also, asking precisely about the part of your code that doesn't work as intended would encourage us to help you with what is obviously some kind of school assignment. – Touffy Nov 02 '17 at 21:16

2 Answers2

0

I have edited your code this way:

function linkedDrawing(canvas,url){


fetch(url)
  .then((response)=> response.json())
  .then((data)=>{
    const c = canvas.getContext('2d');
    console.log(data.url);
    c.beginPath();
    c.moveTo(data.x1, data.y1);
    c.lineTo(data.x2, data.y2);
    c.strokeStyle = data.col;
    c.stroke();
    //added this if to continue as long as we have value for URL. And recursively call the drawing function
    if(data.url) {
        linkedDrawing(canvas, data.url);
     }
  })
}

linkedDrawing(linkedDrawingCanvas, "http://jacek.soc.port.ac.uk/tmp/ws/alpha.json")
0

return the fetch() call from the function and schedule next call to the same function, see also multiple, sequential fetch() Promise

const canvas = document.getElementById("linkedDrawingCanvas");
const c = canvas.getContext('2d');

function draw(response) { 
  return response.json()
  .then(data => {       
    console.log(data.url);
    c.beginPath();
    c.moveTo(data.x1, data.y1);
    c.lineTo(data.x2, data.y2);
    c.strokeStyle = data.col;
    c.stroke();
    if (data.url) {
      return linkedDrawing(linkedDrawingCanvas, data.url).then(draw)
    } else {
      return "complete"
    }
  })
}

function linkedDrawing(canvas,url){
  return fetch(url)
  .then(draw)
}

linkedDrawing(linkedDrawingCanvas, "http://jacek.soc.port.ac.uk/tmp/ws/alpha.json")
guest271314
  • 1
  • 15
  • 104
  • 177