(working in ReactJS)
I am trying to get the correct canvas dom element but I am only able to get an array of elements and I can't seem to use standard array syntax to return the specific element I want to work on.
import React, {Component} from "react";
import "./Mountaincanvas.scss"
const MountainCanvas = () => {
const canvas = document.getElementsByClassName("mountain-canvas");
console.log(canvas)
console.log(canvas[0])
return (
<canvas className="mountain-canvas"/>
)
}
export default MountainCanvas;
The first time I console log the canvas variable I get a HTMLCollection with a single element
HTMLCollection[]
>0: canvas.mountain-canvas
length: 1
__proto__:HTMLCollection
however if I try to just get the first element of the array I get undefined. How do I select just the first element of the array so I can do things like get Context? or simple styling?
If you're trying to get a handle to the canvas in the current component, use a ref :
const MountainCanvas = () => {
const canvas = React.useRef();
if (canvas.current) {
// do stuff with the canvas
}
return (
<canvas ref={canvas} className="mountain-canvas"/>
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.