遍历页面以获取 url 并使用 fetch 更改 url

looping through pages to to get url and change the url using fetch

我希望它能够进入页面中的 url 并获得下一个 url 等等,直到绘图完成

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")

我的 fiddle: http://jsfiddle.net/g1nqkn7h/3/

我已经这样编辑了你的代码:

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")

return 来自函数的 fetch() 调用并安排对同一函数的下一次调用,另请参阅

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")