Putting Random Dots on the Canvas
Notes
- createImageData
- This will grab an array that we can write to, then "put" this on the canvas.
- This is associated with the canvas, created from the 2d context
- We must supply width and height.
- Optionally we can supply other paramters, but this will do
-
const ctx = canvas.getContext("2d") const imageData = ctx.createImageData(width, height)
- This will give us an object that contains a width × height array of four elements
- By default it is width × height × 4
- And at
-
[ row * width + col + 0 ]is the red component of that pixel -
[ row * width + col + 1 ]is the green component of that pixel -
[ row * width + col + 2 ]is the blue component of that pixel -
[ row * width + col + 3 ]is the alpha component of that pixel
-
- These values can be float or int (int by default)
- 0 black, 255 as intense as the color gets.
- or 0 black, 1.0 as intense as the color gets.
- And we will talk about this later.
- Thse are clamped, so they are kept in the right range by default.
- In the end, we can then put this array back on the canvas with putImageData
- reference
- takes
- The image data
- start x
- start y
- Can take other parameters, but this is all we need.
- So let's implement
- I ripped almost everything out of drawing.js
- DrawImage became
export function DrawImage(inset, canvas) { const width= canvas.width const height = canvas.height const ctx = canvas.getContext("2d") const imageData = ctx.createImageData(width, height) DoDots(imageData) ctx.putImageData(imageData,0,0) }
- For
DoDotsfunction DoDots(imageData) { let width = imageData.width let height = imageData.height let data = imageData.data for(let dots = 0; dots < 100; ++dots) { let x = Math.round(Math.random() * width ) let y = Math.round(Math.random() * height ) let offset = (y * width + x) * 4 data[offset + 0] = Math.round(Math.random() * 255) data[offset + 1] = Math.round(Math.random() * 255) data[offset + 2] = Math.round(Math.random() * 255) data[offset + 3] = 255 } }