Closed masakudamatsu closed 3 years ago
First, set up HTML5 Canvas with React
Second, render the color triangle.
With 200 x 200 resolution, we have this:
We do not need to worry about anti-aliasing. It's on by default: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/imageSmoothingEnabled
We do not need to worry about the Retina display issues as mentioned in https://www.html5rocks.com/en/tutorials/canvas/hidpi/
The height
and width
attributes of the canvas
element effectively set the resolution of an image. Canvas methods to draw paths and rectangles will refer to the grid created by height
and width
pixel values.
The actual size of an image can be set with CSS declarations on the canvas
element.
Without specifying height
and width
, it defaults to 300 pixels wide and 150 pixels high. If CSS does not respect the aspect ratio of 2:1, then the image will get distorted.
Source: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_usage
We manage to render a selected color swatch upon clicking the color triangle.
But the shown color code appears to be wrong. Sometimes it's black even if we click the center of the triangle. We need to investigate why.
The reason for a bug mentioned in the previous comment:
useEffect
hook because the reference to the canvas element will not be created until React renders it.useEffect
code block.handleClick
function needs the context object to retrieve the color of the clicked pixel.A solution: Set the context
object as a React state and cascade the useEffects
hooks, then we can use the context
object outside the useEffects
code block.
Next up: Refactor the code along the line of this snippet: https://stackoverflow.com/a/63212430/11847654
Check if Canvas can improve the appearance of the color triangle than SVG