Using HTML Canvas, how can I maintain the border-image width of the left and right border to be the same as the top and bottom?

25 Views Asked by At

I am creating an interactive frame-image website where the user can change the width or height of an image that uses another image for its border (this will be the frame) in React with HTML Canvas.

Initial look: Initial image with width of 500 and height of 700

Adjusted width from 500 to 5000 where the left and right border is not the same as the top and bottom: Adjusted image width from 500 to 5000 but the height remain 700

My current logic for loading the picture and the border image in React is this:

// Some useState code for the canvasRef, canvasWidth, canvasHeight

useEffect(() => {
  const canvas = canvasRef.current
  const ctx = canvas.getContext('2d')


  ctx.clearRect(0, 0, canvas.width, canvas.height)

  // Load the images
    const mainImage = new Image()
    mainImage.src = mainImageSrc // picture

    // border image. the image is actually a picture frame already 
    const borderImage = new Image()
    borderImage.src = borderImageSrc 



  mainImage.onload = () => {
    // Magic numbers for the image to be inside the border not below it
    ctx.drawImage(mainImage, 70, 70, canvasWidth - 135, canvasHeight - 120)
  }

  borderImage.onload = () => {
    ctx.drawImage(borderImage, 0, 0, canvasWidth, canvasHeight)
  }

  return () => {
    mainImage.onload = null // Cleanup
    borderImage.onload = null // Cleanup
  }
}, [canvasWidth, canvasHeight])


<div className="w-1/2">
  <canvas
     ref={canvasRef}
     width={canvasWidth}
     height={canvasHeight}
     className="max-w-full aspect-auto"
  ></canvas>
</div>

The top and bottom border image width are my goal, but the left and right are too wide. I think the border image is stretched. Can someone please help me?

0

There are 0 best solutions below