Developing a unique lattice structure that is enclosed within a specific form

I'm facing a challenge with creating grids in Canvas that are confined within a specific shape. While I can easily create a grid to fit a square, the task becomes trickier when dealing with irregular shapes. Here's my current progress: I aim to limit the grid to exist solely within the shape.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(75, 50);
ctx.lineTo(40, 65);
ctx.lineTo(100, 105);

ctx.lineTo(200, 15);
ctx.fillStyle = 'green';
ctx.fill();


function drawGrid(context) {
  context.globalCompositeOperation = 'destination-out   ';

  for (var x = 40.5; x < 300; x += 10) {
    context.moveTo(x, 0);
    context.lineTo(x, 300);
  }

  for (var y = 0.5; y < 501; y += 10) {
    context.moveTo(0, y);
    context.lineTo(300, y);
  }

  context.strokeStyle = "#ddd";
  context.stroke();
}

drawGrid(ctx)

https://jsfiddle.net/fom9gtb6/

Answer №1

context.globalCompositeOperation = 'destination-out';

must be changed to:

context.globalCompositeOperation = 'destination-out';

Answer №2

To implement this effect, set

context.globalCompositeOperation = 'source-atop';

Refer to the documentation at MDN

This method ensures that the new shape is only visible where it overlaps with the existing content on the canvas.

Using this approach allows strokeStyle to be utilized for the grid without erasing parts of the desired shape, which would occur with destination-out.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to extract a hash from a document's URL

The following code is used: jQuery(document).ready(function() { console.log($(this)); }); After running this code, the object displayed in the console is: [Document mypage.html#weather] How can I retrieve the last ID from this object? In this ...

Ways to verify the successful creation of a child process in NodeJS

I am attempting to use Node JS child_process to open a file as shown below var child_process =require('child_process'); var spawn = child_process.spawn; var exePath='<exe's path>' var filePath='<file path>' v ...

Employ React Hooks for modifying the class names of elements and their related siblings

I have a function component in React hooks that I am working on. The goal is to change the className to 'active' when any element in the list is clicked, and remove the className from the other elements. const SideBar = () =>{ const [active ...

I would like to create a map showing the selected locations by checking them off using checkboxes

How can I draw a road map by selecting locations with checkboxes in form.php? After posting the selected locations to map.php file and assigning them to a $location array, how do I then assign these values to the waypoints array in the javascript calcRoute ...

Transferring data from an Angular variable to an Express backend using a POST request

req.body seems to be coming up empty for me. I've tried adding content-type headers as json, but it's not making a difference. Can anyone point me in the right direction? Thank you. UPDATE: Just to clarify, my Angular frontend is successfully hi ...

Loading SVG images in advance

I am in possession of around one hundred simple SVG images, distributed among five different image folders. These images are currently retrieved on demand when they need to be displayed, which generally works well but occasionally results in flickering tha ...

Converting NodeJS newline delimited strings into an array of objects

What is the method for reading a text file as follows: `{'values': [0,1,0], 'key': 0} {'values': [1,1,0], 'key': 1} {'values': [1,1,0], 'key': 1}` using: var fs = require('fs'); fs. ...

I'm having trouble identifying the cause of the issue with the line breaking

I recently encountered an issue with a script while using the typed.js library. The code is supposed to output 3 lines followed by 1 final line, but it currently only outputs 2 lines and 1 final line. I attempted to fix the code, but it seems to freeze wit ...

Personalize the menu item in material ui

Currently, I have a <select> component from Material UI and I am iterating over the menuItem elements. Here is a sample you can reference: here My issue lies in trying to change the background color of each menu item. Although I attempted to do so, ...

Interactive section for user input

I am looking to add a commenting feature to my website that allows for dynamic editing. Essentially, I want users to be able to click on an "Edit" span next to a comment and have it transform into an editable textarea. Once the user makes their changes and ...

The JavaScript function exclusively reveals the final element, which is Three.js

I'm currently working on a fence generator function using Three.js, but for some reason, my function is only returning the last fence created. It's really puzzling to me... function createFence(nb){ var i; var position = -5; var loadingMan ...

Steps for assigning innerHTML values to elements within a cloned div

Currently, I am setting up a search form and I require dynamically created divs to display the search results. The approach I am taking involves: Creating the necessary HTML elements. Cloning the structure for each result and updating the content of ...

Is requesting transclusion in an Angular directive necessary?

An issue has cropped up below and I'm struggling to figure out the reason behind it. Any suggestions? html, <button ng-click="loadForm()">Load Directive Form</button> <div data-my-form></div> angular, app.directive(&apos ...

Keep sending ajax request until the page is closed

Is it possible to resend an ajax request continuously using pure javascript without any framework? Here is an example of how I am currently attempting to do it: xmlhttp=new XMLHttpRequest(); xmlhttp.open("POST","demo_post2.asp",true); xmlhttp.setRequest ...

eliminate the common elements between two arrays in typescript/javascript

I have two lists of objects, each containing two fields: let users1 = [{ name: 'barney', uuid: 'uuid3'}, { name: 'barney', uuid: 'uuid1'}, { name: 'barney', uuid: 'uuid2 ...

The TypeScript compilation failed for the Next.js module

Working on a project using Next.js with typescript. The dev server was running smoothly, and I could see frontend changes instantly. However, after modifying the next.config.js file and restarting the server (later reverting the changes), compilation issue ...

No action is triggered after submitting AJAX data in a WordPress environment

I'm currently working on developing a WordPress plugin that requires querying the database. However, I am facing challenges in getting it to function properly. Here is the code snippet that I have attempted: jQuery('#demo_ajax').submit(func ...

Utilizing the HTML method of jQuery on a jQuery element

Currently, I am attempting to modify the inner html of an element. When I utilize the following code: $('.best-photos-button')[0].innerHTML="Add More Photos"; the change is successful. However, if I try to use .html() instead of ".innerHTML" in ...

Transforming JavaScript Code into C# Syntax

I could really use some assistance. I've got a JavaScript code snippet here. var regiondb = new Object() regiondb["africa"] = [{value:"1", text:"Cairo"}, {value:"2", text:"Casablanka"}, {value:"3", text:"T ...

The Node.js application encounters a blank response when making a GET request to the API

As a newcomer to node.js, I'm attempting to describe the issue at hand as clearly as possible. If clarification is needed, please let me know. In my current node.js project, I am faced with a challenge where I need to take a code received from the re ...