I am trying to load a local image onto canvas element but it's throwing an error:
Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement or HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or SVGImageElement or VideoFrame)'.
It works fine when I draw or do stuff with canvas window but when I try to import image using image = Image(gImage.default) it breaks? I am trying to follow along a tutorial made for react on Next.js, is it something because of it?
My code:
import React, { useRef, useEffect, useState } from "react";
import Image from "next/image";
const Canvas = (props) => {
const canvasRef = useRef(null)
// load image
const gImage = require("../public/map.png")
const image = Image(gImage.default)
useEffect(() => {
const someTry = () => {
}
const canvas = canvasRef.current
const context = canvas.getContext('2d')
// our first draw
context.fillStyle = "#000000"
context.fillRect(0, 0, context.canvas.width, context.canvas.height)
console.log(image)
someTry()
// const mapImage = document.createElement('img')
// mapImage.src = '../public/map.png'
// context.drawImage(image, 0, 0)
image.onload = () => {
context.drawImage(image, 0, 0)
}
}, [])
return <canvas ref={canvasRef} {...props} width={288} height={480} />
}
export default Canvas
I thought this was something related to getStaticProps but when I try to pass image from there it says Image() method is not defined, so is there any way around this? And why is it happening?
The Image constructor you're trying to use is not from next/image. You should remove import Image from "next/image" from the imports.
You should also move the image variable initialisation inside the useEffect, and set the image's source to "/map.png".
import React, { useRef, useEffect } from "react";
const Canvas = (props) => {
const canvasRef = useRef(null)
useEffect(() => {
const image = new Image()
image.src = "/map.png"
const canvas = canvasRef.current
const context = canvas.getContext('2d')
context.fillStyle = "#000000"
context.fillRect(0, 0, context.canvas.width, context.canvas.height)
image.onload = () => {
context.drawImage(image, 0, 0)
}
}, [])
return <canvas ref={canvasRef} {...props} width={288} height={480} />
}
export default Canvas