JavaScript plug-in or CSS tool that enables the creation of hexagon-shaped images by clipping them

As a beginner in web scripting, I am interested in finding a JavaScript or jQuery plug-in that can crop an image into custom provided dimensions, specifically in the shape of a hexagon (see attached image). Ideally, I would prefer the cropping to be achieved through CSS, but I am open to using any JS or jQuery plugin if necessary.

https://i.sstatic.net/GZKQ5.png

Answer №1

Below is the code snippet that aims to fulfill your requested function:

function polygonalCrop(options) {
    function merge(a, b){
        b=b||{};
        for(var key in b)
            if(b.hasOwnProperty(key))
                a[key] = b[key];
        return a;
    }

    options=merge({
        url:null,
        sides:8,
        angle:0,
        centerX:null,
        centerY:null,
        radius:null,
        outlineColor:null,
        outlineThickness:null,
        success:function(url){},
        fail:function(ev){}
    },options);
    if (!options.url) throw 'options needs an image URL as url property';
    var img=new Image();
    img.setAttribute('crossOrigin', 'anonymous');
    img.onload=function() {
        var w=this.width;
        var h=this.height;
        var canvas=document.createElement('canvas');
        canvas.width=w;
        canvas.height=h;
        var ctx=canvas.getContext('2d');
        if (options.centerX===null) {
            options.centerX=w/2;
        }
        if (options.centerY===null) {
            options.centerY=h/2;
        }
        var ang=2*Math.PI/options.sides;
        var len=Math.sin(ang/2)*2;
        if (options.radius===null) {
            options.radius=Math.min(w/2,h/2)*Math.cos(ang/2);
        }
        ctx.translate(options.centerX,options.centerY);
        ctx.rotate(options.angle);
        if (options.outlineThickness) ctx.lineWidth=options.outlineThickness;
        if (options.outlineColor) ctx.strokeStyle=options.outlineColor;
        ctx.moveTo(-len/2,-options.radius);
        for (var i=0; i<2*Math.PI; i+=ang) {
            ctx.rotate(ang);
            ctx.lineTo(len/2,-options.radius);
        }
        ctx.closePath();
        if (options.outlineThickness && options.outlineColor) ctx.stroke();
        ctx.clip(); 
        ctx.rotate(2*Math.PI-i-options.angle);
        ctx.translate(-options.centerX,-options.centerY);
        ctx.drawImage(this,0,0);
        options.success(ctx.canvas.toDataURL());
    };
    img.onerror=function() { alert('there was an error loading the image'); };
    img.src=options.url;
}

This function takes the provided URL and crop dimensions to generate a cropped image data URL. You can view it live here: https://jsfiddle.net/psrec1b5/2/

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

What is the best method for establishing environment variables across different platforms?

When working with Node scripts on Windows, the format should be like this: "scripts": { "start-docs": "SET NODE_ENV=development&&babel-node ./docs/Server.js" } However, on Linux, the SET command is not used, so it would look like this: "scri ...

What could be causing the mysterious error when using fs.readFileSync?

I am relatively new to coding and I've been working on setting up a warning system for my Discord bot. I have a file that stores the user IDs and their corresponding warning counts. Initially, I was using Node version 12.10.0, but now I'm on vers ...

Scrollable Flexbox Container

In my flex container, I am attempting to create another flex container that will scroll content if it exceeds the screen size. Here is the code I have so far: <Box sx={{ m: 'var(--Content-margin)', p: 'var(--Content-pa ...

JavaScript Closures can utilize a shared global setting object or be passed as an argument to individual functions

Looking for advice on the use of a global "settings object" in relation to JavaScript closures. Should I access it from within functions in the global scope or pass the object every time a function requires access? To provide context, here's a mockup ...

The jQuery library is showing an error message on my AJAX registration form stating: ".JSON.parse: unexpected character error"

Being new to jQuery, I find myself quite confused by its concepts. I recently integrated an AJAX script into my PHP MySQL registration script to allow for form submission without page reloading. However, I keep encountering the following error message: ...

The input elements in HTML code can be dynamically manipulated by Selenium

Recently, I've been utilizing Selenium to automate competition entries on Gleam. Previously, I faced challenges with identifying tags but managed to resolve it by locating the correct iframe. However, the distinctive class tag that allowed me to input ...

Transmit data from an HTML form to PHP using JSON

I am attempting to utilize JavaScript to send POST data. I have the data in an HTML form: <form name="messageact" action=""> <input name="name" type="text" id="username" size="15" /> <input name="massage" type="text" id="usermsg" si ...

Identical identification numbers duplicated in Vuex payload multiple times

I'm working on a shopping cart system for an online store, and I want to be able to add products to the cart with unique IDs attached to each one in vuex. Each ID should be specific to that product instance to ensure that no two identical products hav ...

Can a data object in Vue be automatically updated when there are changes in the database?

I am developing a web application where users can create an account and join rooms. Once inside a room, they have the ability to click a button that randomly selects another user in the room to give a gift to. My challenge lies in updating a data object in ...

Why am I receiving the error message 'Uncaught TypeError: results is not a function' while utilizing the map function?

Struggling to grasp the concept of the map function and puzzled by why my output is showing [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined], even though I've provided the correct this value as per the documenta ...

Unable to access a PHP file within a JavaScript loop

In my HTML document, there is a button with an onclick method inside a JavaScript <script> tag. When this button is clicked, it triggers the deleteRow function, which is responsible for removing a row from a table on the page. Within the deleteRow f ...

Retrieving an array of objects from the database utilizing AJAX

I am trying to retrieve comments from a database and display them on my webpage. However, the current code is throwing a syntax error because the PHP file is not returning the JSON file properly. Here is a snippet of my PHP code (just the fetching part, n ...

Can the <article> tag and all its content be positioned in the center of the webpage?

Can the <article> and its content remain centrally aligned on the page? Check out my website here: Typically, when you visit a website, the article is positioned in the center of the page. However, in my case, the article only remains centered when ...

How can I implement custom color values for individual sides of the border property in tailwind-css?

I am attempting to utilize tailwind to create a triangle shape. Here is the original code I found on the Triangle Generator. To assign colors to each side of the border, I am using the border-b-color syntax with pre-defined theme colors, which works well. ...

Vue.js fails to display multiple uploaded images

I have been working on implementing a multiple image upload feature using vue.js. So far, everything seems to be functioning correctly. However, I am facing an issue where the HTML does not display thumbnails of the images I have selected. Additionally, I ...

JavaScript Function to Redirect Page After a Delay of X Seconds

I'm trying to implement a redirect to a specific URL after displaying an error message for 5 seconds. Initially, I used JavaScript like this: document.ready(window.setTimeout(location.href = "https://www.google.co.in",5000)); However, the redirectio ...

Rules for specifying title attribute for tag a in JavaScript

What is the best way to handle conditions for the a tag (links) when it has content in the title attribute? If there is no description available, how should the script be used? For instance: if ( $('a').attr('title') == 'on any ...

Changing the appearance of a webpage using awk or gawk

Looking to make modifications to specific CSS styles using awk/gawk. For instance, how can I alter the right property of the cta_grad style?: .cta_grad { cursor: pointer; cursor: hand; position: absolute; bottom: 38px; right: 34px; ...

Unable to increase value in interface field

I am working with an array of objects that represent interfaces. Once this array is created, each object needs to have a value incremented inside it. Specifically from 'x1' to 'x2'. After the iteration, all the 'x1' and &apo ...

Error encountered when attempting to trigger a Bootstrap dropdown within a designated div

When using React JS, I encountered an issue when trying to trigger a dropdown that was nested inside a div with the class name "row". Initially, I placed the data-toggle and data-target attributes inside the div, like so: <div className="row"> < ...