Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Brush effect on page through canvas

I am working on functionality where I have to create a brush-like an effect on the web page.

The requirement is that there will be multiple patterns/textures available in the background. And the user will drag the mouse to create the effect of that pattern on the page.

Below is the JSFiddle link where I have created the structure, I am able to create the pattern, but I am unsure of how to create the brush-like effect.

I have added the brush image as a data source in my JSFiddle Link

I am a beginner in canvas and don't have any idea about how to move forward. Please let me know if I am going in the right direction.

Check the Reference Website where this functionality is running and working.

like image 378
Varun Chakervarti Avatar asked Nov 30 '25 02:11

Varun Chakervarti


1 Answers

Well for a basic brush effect, instead of drawing a single large dot, you can instead draw a bunch of smaller dots, each dot representing a single brush stroke. You can also add variable width to the strokes if you want but that is upto you. This is a basic brush example, instead of drawing a circle, draw it like this: JS Fiddle

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let drawCheck = false;
ctx.strokeStyle = "#808080";
let points = 40;
let offsets = [];
let radius = 50;
let prev = {
  x: -1,
  y: -1
};
let curr = {
  x: -1,
  y: -1
};

for (let i = 0; i < points; i++) {
  offsets.push([Math.random() * radius * (-1) ** i, Math.random() * radius * (-1) ** i, 1 + Math.random() * 4]);
}

function draw(x, y) {
  curr.x = x;
  curr.y = y;

  if (drawCheck) {
    if (prev.x == -1) {
      offsets.forEach(offset => {
        ctx.beginPath();
        ctx.arc(curr.x + offset[0], curr.y + offset[1], 1, 0, 2 * Math.PI);
        ctx.fill();
        prev.x = curr.x;
        prev.y = curr.y;
      });
    } else {
      offsets.forEach(offset => {
      ctx.lineWidth = offset[2];
        ctx.beginPath();
        ctx.moveTo(prev.x + offset[0], prev.y + offset[1]);
        ctx.lineTo(curr.x + offset[0], curr.y + offset[1]);
        ctx.stroke();
      })
      prev.x = curr.x;
      prev.y = curr.y;
    }

  }
}

document.addEventListener("mousedown", (e) => drawCheck = true);
document.addEventListener("mousemove", (e) =>
  draw(e.clientX, e.clientY));
document.addEventListener("mouseup", (e) => {
  drawCheck = false;
  prev = {
    "x": -1,
    "y": -1
  };
});
#canvas {
  border: 2px solid black;
}
<html>
<head>
</head>
<body>
<canvas id="canvas" height=320 width=600></canvas>
</body>
</html>
like image 99
Garvit Joshi Avatar answered Dec 02 '25 14:12

Garvit Joshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!