简体   繁体   中英

Javascript / jQuery UI: Changing element img src from an array of images based on current img src

I have a canvas element containing an image, which is initially a Green Square. I'm trying to change the displayed image based on the input from two sets of jQuery UI radio buttons: the first set allows the user to select a colour and has 3 options (Red/Green/Blue), and the second set allows the user to select a shape (Circle/Square).

My Javascript code declares an array of images, one of which is then assigned to display in the canvas element when a button option is checked, like so:

var images = new Array();

images[0] = new Image();
images[0].src = '../../../media/images/Red-Circle.png';

images[1] = new Image();
images[1].src = '../../../media/images/Red-Square.png';

images[2] = new Image();
images[2].src = '../../../media/images/Green-Circle.png';

images[3] = new Image();
images[3].src = '../../../media/images/Green-Square.png';

images[4] = new Image();
images[4].src = '../../../media/images/Blue-Circle.png';

images[5] = new Image();
images[5].src = '../../../media/images/Blue-Square.png';


$(function () {
    $("#colour").buttonset();
    $("#shape").buttonset();
});

$('#red').click(function () {
    if ($('#red').is(':checked')) {
        $("#container #image img").attr("src", images[1].src);
    }
});

$('#green').click(function () {
    if ($('#green').is(':checked')) {
        $("#container #image img").attr("src", images[3].src);
    }
});

$('#blue').click(function () {
    if ($('#blue').is(':checked')) {
        $("#container #image img").attr("src", images[5].src);
    }
});

HTML:

<div id="container">
     <div id="image">
          <img src="media/images/Green-Square.png" />
     </div>
</div>

<form>
     <div id="colour">
          <input type="radio" id="red" name="radio">
          <label for="colour1">Red</label>
          <input type="radio" id="green" name="radio" checked="checked">
          <label for="colour2">Green</label>
          <input type="radio" id="blue" name="radio">
          <label for="colour3">Blue</label>
     </div>
</form>
<form>
     <div id="shape">
          <input type="radio" id="circle" name="radio">
          <label for="circle">Circle</label>
          <input type="radio" id="square" name="radio" checked="checked">
          <label for="square">Square</label>
     </div>
</form>

I've only got as far as being able to select the colour. When it comes to selecting the shape, I want to change the displayed image to retain the previous choice of colour (so that for example, if Red was the currently selected colour and the user then selected Circle, the image displayed would change to a Red Circle and not a Green or Blue Circle). Conversely, if the user selected the shape first and THEN selected a colour, I want the displayed image to retain the choice of shape.

I have a vague idea that the solution might be to do with adding 1 or subtracting 1 from the array index based on what the current index is - but I have no clue how to implement this. I'm relatively new to JS so any help would be appreciated. Thanks.

Here is an plunker for what you are trying to do.

https://plnkr.co/edit/jMvjJCxHZzr9dxw5B6RR?p=preview

the function you will require are

$('#circle').change(function () {
if ($('#circle').is(':checked')) {


    var a = jQuery.grep(images, function( n ,i) {
      if ( n.src == $("#container #image img").attr("src") )
      return i;
    })[0];

    var index = images.indexOf(a);

    $("#container #image img").attr("src", images[index-1].src);
}

});

    $('#square').change(function () {
    if ($('#square').is(':checked')) {
   var a = jQuery.grep(images, function( n ,i) {
      if ( n.src == $("#container #image img").attr("src") )
      return i;
    })[0];

    var index = images.indexOf(a);

    $("#container #image img").attr("src", images[index+1].src);
}

The color select button logic is not correct as well please use this logic there as well.

You can store your images in an 'images' object and access them by string (ex images["RedSquare"]) I've put together a fiddle. The image links are broken but if you inspect the page you can see the src is being changed properly.

https://jsfiddle.net/5wv5ym5p/

HTML:

<div id="container">
            <div id="image">
                <img src="media/images/Green-Square.png" />
            </div>
        </div>

        <form>
            <div class="shape-config" id="colour">
                <input type="radio" id="red" name="radio">
                <label for="red">Red</label>
                <input type="radio" id="green" name="radio" checked="checked">
                <label for="green">Green</label>
                <input type="radio" id="blue" name="radio">
                <label for="blue">Blue</label>
            </div>
        </form>
        <form>
            <div class="shape-config" id="shape">
                <input type="radio" id="circle" name="radio">
                <label for="circle">Circle</label>
                <input type="radio" id="square" name="radio" checked="checked">
                <label for="square">Square</label>
            </div>
        </form>

JS (needs JQuery):

var images = {};

images["RedCircle"] = new Image();
images["RedCircle"].src = '../../../media/images/Red-Circle.png';

images["RedSquare"] = new Image();
images["RedSquare"].src = '../../../media/images/Red-Square.png';

images["GreenCircle"] = new Image();
images["GreenCircle"].src = '../../../media/images/Green-Circle.png';

images["GreenSquare"] = new Image();
images["GreenSquare"].src = '../../../media/images/Green-Square.png';

images["BlueCircle"] = new Image();
images["BlueCircle"].src = '../../../media/images/Blue-Circle.png';

images["BlueSquare"] = new Image();
images["BlueSquare"].src = '../../../media/images/Blue-Square.png';


$(function () {
    $("#colour").buttonset();
    $("#shape").buttonset();
});

$('.shape-config input').click(function () {
        var colourId = $("#colour input:checked").attr("id");
    var colour = $('label[for='+colourId+']').text();
    var shapeId = $("#shape input:checked").attr("id");
    var shape = $('label[for='+shapeId+']').text();
        $("#container #image img").attr("src", images[colour+""+shape].src);
});

Why bother using arrays/indexes and storing it at all?

https://jsfiddle.net/0Lqgc3vx/

HTML

<img id="img" src="Green-Square.png" />

<form>
    <input type="radio" name="colour" value="Red">
    <label for="colour1">Red</label>
    <input type="radio" name="colour" value="Green" checked="checked">
    <label for="colour2">Green</label>
    <input type="radio" name="colour" value="Blue">
    <label for="colour3">Blue</label>
</form>

<form>
    <input type="radio" name="shape" value="Circle">
    <label for="circle">Circle</label>
    <input type="radio" name="shape" value="Square" checked="checked">
    <label for="square">Square</label>
</form>

JS

$("input[name='colour']").change(function () {
    $("#img").attr("src", this.value + "-" + $("input[name='shape']:checked").val() + ".png");
});

$("input[name='shape']").change(function () {
    $("#img").attr("src", $("input[name='colour']:checked").val() + "-" + this.value + ".png");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM