Show picture depending on the button pressed

Is it possible to only display the selected image? I have a set of buttons that allow customers to customize an image.

For example, the user selects a shape like a circle, which is then displayed. The next step involves selecting a pattern to display inside the circle. I want the transparent part of the shapes (circle, rectangle, and heart) to be visible only on the inside.

Here's the code snippet:

function display(){

if (document.getElementById('shape1').checked)   
    {
    var ctx = document.getElementById('display_image').getContext('2d');
    var imageObj = new Image();
     imageObj.onload = function()
     {  ctx.drawImage(imageObj, 0, 0); }
     
     imageObj.src = 'http://image.flaticon.com/icons/png/512/33/33848.png';
     }
     
     
     if (document.getElementById('shape2').checked)   
    {
    var ctx = document.getElementById('display_image').getContext('2d');
    var imageObj = new Image();
     imageObj.onload = function()
     {  ctx.drawImage(imageObj, 0, 0); }
     
     imageObj.src = 'http://image.flaticon.com/icons/png/512/33/33848.png';
     }
}

     if (document.getElementById('pattern1').checked)   
    {
    var ctx = document.getElementById('display_image').getContext('2d');
    var imageObj = new Image();
     imageObj.onload = function()
     {  ctx.drawImage(imageObj, 0, 0); }
     
     imageObj.src = 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTw_LgFWAcL6RzFH4EApgo69TX7xx6iUyPqLANgi5qdJ6QL9CY';
     }
}

     if (document.getElementById('pattern2').checked)   
    {
    var ctx = document.getElementById('display_image').getContext('2d');
    var imageObj = new Image();
     imageObj.onload = function()
     {  ctx.drawImage(imageObj, 0, 0); }
     
     imageObj.src = 'https://s-media-cache-ak0.pinimg.com/originals/8b/09/59/8b0959d17298294904713dbb94b00827.png';
     }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


 <form role="form" id="showchoices" name="showchoices" method="post">

<div> <input type="radio" id="shape1" name="shape_design" value="CIRCLE" onchange="display()"/> O 
<input type="radio" id="shape2" name="shape_design" value="RECTANGLE" onchange="display()"/> [] </div>

<div> <input type="radio" id="pattern1" name="pat_design" value="pattern2" onchange="display()"/> pattern1  
<input type="radio" id="pattern2" name="pat_design" value="pattern1" onchange="display()"/> pattern2 </div> -- i would like the pattern not to overlap the shape, send to back and visible.
</form>

<div id="display_image" name="display_image" width="400px" height="400px"> </div>

The functionality I am looking for is similar to this example, but without the animation. The radio buttons trigger the display of images in a static manner. -- http://jsfiddle.net/djnBD/

I am also trying to incorporate this process into the following sample - https://jsfiddle.net/Twisty/955j8so3/27/

THANK YOU IN ADVANCE!!!

Answer №1

Here's a brief illustration of how you can achieve your desired outcome using HTML and jQuery. I hope this example proves to be beneficial.

$(document).ready(function(){
  $(document).on("click", "*[data-toggle='add-img']", function() {
var newImgSrc  = $(this).attr("data-img"); 
var newImgId   = $(this).attr("data-img-id"); 
var newImg     = "<img src='"+newImgSrc+"' id='"+newImgId+"' />";
appendToContainer(newImg, newImgId);
  });
  $(document).on("click","*[data-toggle='remove-img']", function() {
    var newImgId= $(this).attr("data-img-id"); 
    if ($("#"+newImgId).length>0) $("#"+newImgId).remove();
  });

  function appendToContainer(img, imgId) {
  var imgContainer= $("#images-container");
  var zIndex= imgContainer.children("img").last().css("z-index");
  var newZIndex= parseInt(zIndex)+1;
  if ($("#imgId").length===0) imgContainer.append(img);
 $("#imgId").css({"z-index":newZIndex});
  }
});
#images-container > img {
  position: absolute;
  top: 40;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<div>
  <a href="#" data-toggle="add-img" data-img="http://image.flaticon.com/icons/png/512/33/33848.png" data-img-id="img1">img 1</a>
  <a href="#" data-toggle="add-img" data-img="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTw_LgFWAcL6RzFH4EApgo69TX7xx6iUyPqLANgi5qdJ6QL9CY" data-img-id="img2">img 2</a>
  <a href="#" data-toggle="add-img" data-img="https://s-media-cache-ak0.pinimg.com/originals/8b/09/59/8b0959d17298294904713dbb94b00827.png" data-img-id="img3">img 3</a>
  
  <a href="#" data-toggle="remove-img" data-img-id="img1">delete img 1</a>
  <a href="#" data-toggle="remove-img" data-img-id="img2">delete img 2</a>
  <a href="#" data-toggle="remove-img" data-img-id="img3">delete img 3</a>
</div>

<div id="images-container"></div>

Answer №2

After experimenting with canvas, I was able to achieve the desired outcome:

function display(){

if (document.getElementById('shape1').checked)   
    {
    var ctx = document.getElementById('display_image').getContext('2d');
    var imageObj = new Image();
     imageObj.onload = function()
     {  ctx.drawImage(imageObj, 0, 0); }
     
     imageObj.src = 'http://image.flaticon.com/icons/png/512/33/33848.png';
     }
     
     
     if (document.getElementById('shape2').checked)   
    {
    var ctx = document.getElementById('display_image').getContext('2d');
    var imageObj = new Image();
     imageObj.onload = function()
     {  ctx.drawImage(imageObj, 0, 0); }
     
     imageObj.src = 'http://image.flaticon.com/icons/png/512/33/33848.png';
     }
}

     if (document.getElementById('pattern1').checked)   
    {
    var ctx = document.getElementById('display_image').getContext('2d');
    var imageObj = new Image();
     imageObj.onload = function()
     {  ctx.drawImage(imageObj, 0, 0); }
     
     imageObj.src = 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTw_LgFWAcL6RzFH4EApgo69TX7xx6iUyPqLANgi5qdJ6QL9CY';
     }
}

     if (document.getElementById('pattern2').checked)   
    {
    var ctx = document.getElementById('display_image').getContext('2d');
    var imageObj = new Image();
     imageObj.onload = function()
     {  ctx.drawImage(imageObj, 0, 0); }
     
     imageObj.src = 'https://s-media-cache-ak0.pinimg.com/originals/8b/09/59/8b0959d17298294904713dbb94b00827.png';
     }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



 <form role="form" id="showchoices" name="showchoices" method="post">

<div> <input type="radio" id="shape1" name="shape_design" value="CIRCLE" onchange="display()"/> O 
<input type="radio" id="shape2" name="shape_design" value="RECTANGLE" onchange="display()"/> [] </div>

<div> <input type="radio" id="pattern1" name="pat_design" value="pattern2" onchange="display()"/> pattern1  
<input type="radio" id="pattern2" name="pat_design" value="pattern1" onchange="display()"/> pattern2 </div> -- i would like the pattern not to overlap the shape, send to back and visible.
</form>

<canvas id="display_image" name="display_image" width="400px" height="400px"> </canvas>

Although it might not render correctly here, it functions well in my actual code implementation.

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

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...

Function executed many times during click action

I have developed a web application that allows users to input any keyword or statement and receive twenty results from Wikipedia using the Wikipedia API. The AJAX functionality is working perfectly. The app should dynamically create a DIV to display each r ...

Using Webpack postcss prefixer with Vue CLI 3

As I work on implementing Bulma CSS in my project using Vue CLI 3, I encounter the need to prefix the classes with webpack. While I found an example of this process, adapting it from a webpack config to vue.config.js poses some challenges. Here is the ini ...

Is there a way in Vue.js for me to access a method from within the same component using the component's data?

Below is the code for a specific component: <template> <li v-for="(item, i) in this.menu" :key="i" @click="item.action()"> //attempting to call the method in the component {{menu.title}} <li> </template> <script> ...

Searching for data within an array of objects that contain multiple key-value pairs in the form of arrays: A step-by-step guide

For instance const information = [ { companies: [ {name: 'Yuri'}, {name: 'Boeing'}, {name: 'Laser'}, ], sectors: [ {name: 'Logistic'}, {name: 'Aviati ...

Conceal all div elements except for displaying the initial two

Can an entire div be hidden with only the first 2 entities visible? <div class="inline-edit-col"> <span class="title inline-edit-categories-label">Brands</span> <ul class="cat-checklist product_brand-checklist"> < ...

Make the div stretch across the entire width of the page, excluding the width of a fixed div located on the right side, without needing to set a margin-right property

I've been struggling to find a solution for my wiki development project. My challenge involves designing a page layout with a fixed-width sidebar on the right, while ensuring that content to the left of the sidebar adjusts its width accordingly. I wan ...

Resetting the file input in ReactJS can be easily accomplished by setting

My upload input field: <input onChange={this.uploadFile} id="fileUpload" type="file" className="upload"/> This is how I handle the uploads: uploadFile(e) { e.preventDefault(); let reader = new FileReader(); let file = e.target.files[0] ...

What is the correct way to utilize Microdata fields?

I'm finding the process of creating a list of events on a page to be a bit perplexing. Does the URL in this example represent the current page or another page you are mentioning? <div itemscope itemtype="http://data-vocabulary.org/Person"> H ...

Determining the availability of a remote source in React: A step-by-step guide

Is there a way to verify the existence of a remote resource, such as a large zip file, without actually downloading the file? What is the most efficient method for checking the presence of the resource? ...

JavaScript: Responding to the fetch response based on certain conditions

I am currently working with a fetch() request that can either return a zip file (blob) or a JSON object in case of an error. The existing code successfully handles the zip file by sending it to the user's Downloads folder. However, when a JSON respons ...

The horizontal center alignment of text is not working properly in Bootstrap v5.0

I'm currently learning Bootstrap v5.0 and working on creating a practice webpage with it. However, I've encountered an issue where the text is not aligning center horizontally. Despite using align-items-center, the centering is not working as int ...

The Firebase Authentication module encountered an uncaught error: [$injector:modulerr]

I encountered a challenge while developing a small task for Gmail user login and logout using Firebase authentication. The issue in my code is Uncaught Error: [$injector:modulerr] The libraries I included are: <script src='https://cdn.firebase.co ...

The background image's fadeInOut transitions create a strange phenomenon where all the text appears in white

So, here's a strange issue I'm facing. On my website, the background image changes with a smooth fadeIn/Out transition. Video: Website in action: Here is the HTML markup: <div class="fondo" onclick="descargar(2,500);descargar(1,500);"> ...

Anyone faced the issue of jquery_ujs corrupting the callback URL in Rails 4, causing problems with updating screens via Ajax?

Encountering a Catch-22 situation with jQuery in my Rails app - when I include jquery_ujs, it pulls the wrong URL from Rails during execution, leading to quiet errors when attempting to access non-existent URLs on the server. However, if I omit jquery_ujs ...

Is there a way to adjust the contrast of an image using an HTML slider and JavaScript without utilizing the canvas element?

Looking to develop a slider with HTML and JavaScript (or jQuery, CSV,...) that can adjust the contrast of an image, similar to this topic. However, I would prefer not to utilize Canvas in HTML5 for this project. Any suggestions on how to achieve this with ...

What is the best way to direct attention to the HTML5 canvas element?

I'm having an issue with the HTML5 <canvas> element in Firefox 2.0.0.16 and Safari 3.1.2 on my iMac. Even testing in Firefox 3.0 on Windows did not resolve the problem. Here is the code snippet that seems to be causing the trouble: <td> ...

Seasonal selection tool

I need a quarterly date picker feature, ideally using Angular. I am interested in something similar to the example shown below: https://i.stack.imgur.com/9i0Cl.png It appears that neither Bootstrap nor (Angular) Material have this capability. Are there a ...

django.http.request.RawPostDataException: It is not possible to retrieve the body content once the request's data stream has been read

I encountered an error while making an API, it's showing django.http.request.RawPostDataException: You cannot access body after reading from the request's data stream. I believe you can't access data a second time. Here is my code: def get_p ...

Deselect Certain Categories of Automatically Generated Tick Boxes

I have implemented some visually appealing "checkboxes" using li, span, and bootstrap glyphicon elements. These checkboxes display an active state when checked by adding the .active class. Upon activation of the active class, a hidden div beneath the boot ...