Categories
JavaScript Answers

How to fill rectangle with pattern with JavaScript?

Spread the love

Sometimes, we want to fill rectangle with pattern with JavaScript.

In this article, we’ll look at how to fill rectangle with pattern with JavaScript.

How to fill rectangle with pattern with JavaScript?

To fill rectangle with pattern with JavaScript, we can use d3.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.3.0/d3.min.js"></script>

to add the d3 script.

Then we write:

const svg = d3.select("body").append("svg");

svg
  .append('defs')
  .append('pattern')
  .attr('id', 'diagonalHatch')
  .attr('patternUnits', 'userSpaceOnUse')
  .attr('width', 4)
  .attr('height', 4)
  .append('path')
  .attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2')
  .attr('stroke', '#000000')
  .attr('stroke-width', 1);

svg.append("rect")
  .attr("x", 0)
  .attr("width", 100)
  .attr("height", 100)
  .style("fill", 'orange');

svg.append("rect")
  .attr("x", 0)
  .attr("width", 100)
  .attr("height", 100)
  .attr('fill', 'url(#diagonalHatch)');

to create an svg element and append it to the body as its child with

const svg = d3.select("body").append("svg");

Then we write

svg
  .append('defs')
  .append('pattern')
  .attr('id', 'diagonalHatch')
  .attr('patternUnits', 'userSpaceOnUse')
  .attr('width', 4)
  .attr('height', 4)
  .append('path')
  .attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2')
  .attr('stroke', '#000000')
  .attr('stroke-width', 1);

to add the diagonal hatch pattern.

We add the width, height stroke, stroke-width, etc with attr.

We set the 'id' of the pattern so we can apply it later by referencing its ID.

Next, we add the rectangle with

svg.append("rect")
  .attr("x", 0)
  .attr("width", 100)
  .attr("height", 100)
  .style("fill", 'orange');

And we set width, height and fill of the rectangle with attr.

Finally, we append the diagonal hatch pattern we created with

svg.append("rect")
  .attr("x", 0)
  .attr("width", 100)
  .attr("height", 100)
  .attr('fill', 'url(#diagonalHatch)');

We call attr with 'fill' and 'url(#diagonalHatch)' to apply the diagonalHatch pattern we created earlier.

Conclusion

To fill rectangle with pattern with JavaScript, we can use d3.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *