Search code examples
javascriptcanvashtml5-canvas

Html canvas how to draw a rectangle for each element of an array


I am trying to draw a rectangle for each element of an array using HTML5 Canvas.

Here is my code, it doesn't draw anything to the canvas:

let x_arr= [100,200,300]
let y_arr= [200,300,400]

var canvas= document.getElementById("myCanvas")
var cursor= canvas.getContext("2d")
cursor.fillStyle = "#FF0000";
cursor.fillRect(50, 50, 4, 4);
cursor.stroke()

function draw_element(item, index){
  cursor.rect(item, y_arr[index], 10, 10)
  cursor.fill()
}

setInterval(x_arr.forEach(draw_element), 1000)

Note that I want to update the drawing every second that's why I called the forEach() in the setInterval()


Solution

  • setInterval takes a function as an argument

    let x_arr = [100, 200, 300]
    let y_arr = [200, 300, 400]
    
    var canvas = document.getElementById("myCanvas")
    var cursor = canvas.getContext("2d")
    cursor.fillStyle = "#FF0000";
    cursor.fillRect(50, 50, 4, 4);
    cursor.stroke()
    
    function draw_element(item, index) {
      cursor.rect(item, y_arr[index], 10, 10)
      cursor.fill()
    }
    
    setInterval(() => x_arr.forEach(draw_element), 1000)
    <canvas width="500" height="500" id="myCanvas"></canvas>