Languages
[Edit]
EN

JavaScript - how to draw pixel on canvas element?

7 points
Created by:
Majid-Hajibaba
972

In JavaScript, it is not possible to get direct access to a single pixel on the canvas element, but there are some tricks on how to do it. In this article, simple approaches have been presented.

Quick solution:

 

Presented solutions in the article:

  1. drawing 1x1 px rectangle on canvas with fillRect(),
  2. drawing 1x1 px image on canvas with putImageData(),
  3. drawing multiple pixels on created image data
    (~double buffering with createImageData() and putImageData()).

Performance test (on Ryzen 9 5900x and GeForce GTX 970):

Draw single pixel on canvas performance test.
Draw single pixel on the canvas performance test.

Hint: running the below examples pay attention on the time necessary to draw pixels.

 

1. Drawing single pixel with fillRect() method example

Edit

This approach is useful when we want to draw single pixels on existing drawing.

 

2. putImageData method with single-pixel class example

Edit

This approach is useful when we want to draw single pixels on existing drawing.

Note: this solution has weak perfomrance.

 

3. putImageData method with ~double buffering example

Edit

This approach is useful when we want to draw everything by own.

Note: this solution has very good perfomrance.

 

See also

Edit
  1. JavaScript - how to draw point on canvas element? 

Alternative titles

  1. JavaScript - set pixel on canvas element
  2. JavaScript - put pixel to canvas element
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - HTML5 canvas tutorial

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join