Generate 10k Canvas Blocks with custom image

by ahmedzafar

HTML

<div id="app"></div>

React

const { useState, useEffect, useRef } = React;


const Canvas = (props) => {
	const x = useRef(0)
  const y = useRef(0)
  const canvasRef = useRef(null)
    
  const draw = ctx => {
    var cols = 100;
    var rows = 100; 
    for(var i = 0; i < cols; i++){
      for(var j = 0; j < rows; j++){
        x.current = i * 10
        y.current = j * 10
        ctx.strokeRect(x.current, y.current, 10, 10)
      } 
    }
  }

  const drawImg = (ctx) => {
    var img = new Image();   // Create new img element
    img.width = 20;
    img.height = 20;
    img.setAttribute('class','imgURL')
		img.src = 'https://camo.githubusercontent.com/48d099290b4cb2d7937bcd96e8497cf1845b54a810a6432c70cf944b60b40c77/68747470733a2f2f7261776769742e636f6d2f676f72616e67616a69632f72656163742d69636f6e732f6d61737465722f72656163742d69636f6e732e737667'
    img.onload = () => {
      ctx.drawImage(img, 20, 20,img.width,img.height);
    }
  }

  
  const getPosition = () => {
    // console.log('id: ' + canvasRef.current.id)
  }

  useEffect(() => {
    const canvas = canvasRef.current
    canvas.width = 1000;
    canvas.height = 1000;
    console.log(canvasRef.current)
    const context = canvas.getContext('2d')

    //Our draw came here
    draw(context)
    drawImg(context);

  }, [draw,x,y,getPosition])

    return (
        <div id="main-container">

				<button id="new-array-button">Buy Blocks</button>
				<button id="merge-sort-button">Update your blocks with your image</button>
      
            <div id="bar-container">

							<canvas
								ref={canvasRef}
								{...props}
								onClick={getPosition}
							></canvas>

            </div>
        </div>
    )
}

const root = ReactDOM.createRoot(document.querySelector("#app"))
root.render(
  <React.StrictMode>
    <Canvas />
  </React.StrictMode>
);