Search code examples
javascriptvue.jsp5.js

Drawn pixel using pencil on canvas is not centred


I am drawing pixels using a pencil on canvas using p5.js. The issue is that when the pencil size is 1 or smaller in that scenario, its position is not centered. It's coming left right not centered.

I've noticed an interesting observation in our code. It appears that when the mouse's x and y positions are close to .5, the drawn pixel appears centered; however, in other instances, the pixel seems to be slightly off-center. To tackle this, I'm thinking of refining our rendering logic. I'll make sure to set the pixel density to 1 to prevent any automatic scaling issues. Additionally, I might experiment with adjusting the pixel position by incorporating a correction factor, perhaps subtracting 0.5 from both the x and y coordinates. It's crucial to scrutinize any transformations or scaling operations in our code that could be influencing the exact placement of pixels.

I've noticed that the P5.image.set method doesn't seem to accept floating-point numbers; it rounds to the nearest integer. Has anyone found a workaround for this issue, or am I missing something in the documentation?

Here is the code. Here is the deployed application.

Steps to generate the issue:-

  1. open the link
  2. zoom(mouspress+wheel)
  3. select pencil
  4. mouse press on canvas

Thanks in advance. If any query comments I will add more clarity.

Below is the code of mousepressed method in the for loop we are setting pixel values

mousePressed(mouseX, mouseY) {
      if (this.menuSelection === 'drawPencil') {
        this.mapImage.loadPixels()
        let size = 1
        let y = mouseY
        for (let i = mouseX - size / 2; i < mouseX + size / 2; i++) {
          for (let j = y - size / 2; j < y + size / 2; j++) {
            this.mapImage.set(i, j, this.p5.color(255))
            //console.log('i,j', i, j)
          }
        }
        this.mapImage.updatePixels()
        return
      }
    },

enter image description here


Solution

  • You have said:

    I've noticed that the P5.image.set method doesn't seem to accept floating-point numbers; it rounds to the nearest integer. Has anyone found a workaround for this issue, or am I missing something in the documentation?

    Because of this you need to floor the values always,

    So 0.9 must be set to 0 even though it is closer to 1. so you should floor any float number before passing it to P5.image.set method.

    enter image description here

    For example: the image here scaled up to fit the screen, so in this image if you click on the green area you will select pixel A instead of B (this caused by rounding the float values) if you floor the values yourself it will select B