Search code examples
htmlcanvasswitch-statementradio-buttoncase

Displaying different images on an HTML canvas according to selected radio button


Using this project, you are supposed to be able to select a radio button for a specific color, click the big blue button, and a corresponding 150x150px color swatch will be drawn on an HTML canvas. I've gotten everything down up until the part where the image is to be displayed. I'm stuck on the switch statement.

I've also made a JSFiddle for this:

https://jsfiddle.net/sheradon/yuqqono6/12/

$(document).ready(function() 
{       

var tabClicked = true;
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var imgArray = new Array();

imgArray[0] = new Image();
imgArray[0].src = 'http://i.imgur.com/utPXYZM.jpg';

imgArray[1] = new Image();
imgArray[1].src = 'http://i.imgur.com/j7CfXVF.jpg';

imgArray[2] = new Image();
imgArray[2].src = 'http://i.imgur.com/muNhjqq.jpg';

imgArray[3] = new Image();
imgArray[3].src = 'http://i.imgur.com/SSSSvkD.jpg';

imgArray[4] = new Image();
imgArray[4].src = 'http://i.imgur.com/KMCsKTX.jpg';

imgArray[5] = new Image();
imgArray[5].src = 'http://i.imgur.com/QNe0jAr.jpg';

imgArray[6] = new Image();
imgArray[6].src = 'http://i.imgur.com/QbzmJlE.jpg';

    $('#colorstab').click(function() 
    {        
        if(tabClicked == true)     
        {                
        $('#colorstab').animate(    
        {                
            marginTop:'-8px'      
        }, 0 );                                       
    $('#colorsbox').toggle();       
        tabClicked = false;        
        } else {                                     
        $('.radiobutton').prop('checked', false);    
        $('#colorstab').animate(              
        {                                
            marginTop:'83px'       
        }, 0);           
    $('#colorsbox').toggle();                    
    tabClicked = true;                            
    }
    });
});

function doButtonStuff() 
{
        console.log('Button is working');
    var radioButton = document.getElementsByName('selection');
    for (var i = 0; i < document.filterform.selection.length; i++) 
    {    
        if (document.filterform.selection[i].checked)              
        {
        var radioValue = document.filterform.selection[i].value;    
            alert(radioValue);
        return radioValue;
        }
    switch (document.getElementById('canvas'))
    {
        case (radioValue == 'cyan'):
            canvas.getContext('2d').drawImage(imgArray[6],0,0);
            break;
    }
    }
}

Solution

  • This is not how switch statements work.

    Switch statements compare one value to multiple other values. Take this as an example:

    var inputValue = document.getElementById('favorite-color-input').value;
    switch (inputValue) { // compare the input value
      case 'green':       // if 'inputValue' === 'green', execute the following block
        console.log('your favorite color is green');
        break;            // don't execute the next case block
      case 'blue':        // if 'inputValue' === 'blue', execute the following block
        console.log('...');
        break;
      default:           // neither green nor blue
        console.log('I don\'t know that color');
    }
    

    So your switch statement should look like this:

    switch (radioValue) {
      case 'cyan': // draw the cyan image
        ctx.drawImage(imgArray[6],0,0);
        break;
      case 'pink': // draw the pink image
        ctx.drawImage(imgArray[...],0,0);
        break;
    }
    

    Note that you return radioValue before executing the switch statement. I think that is not what you want. Also, instead of always getting the drawing context of the canvas (canvas.getContext('2d')), use ctx.

    However, there is a reason why you see switch statements so rarely in JavaScript: in most cases, you don't need them. Consider creating an object containing all the images:

    // map every color to the source of the corresponding image
    var imageSources = {
      'cyan': 'http://i.imgur.com/QbzmJlE.jpg',
      'pink': '...'
    };
    var images = {};
    // map every color to the corresponding image
    for (var color in imageSources) {
      images[color] = new Image();
      images[color].src = imageSources[color];
    }
    

    images now looks like:

    { 
      'cyan': <img src="http://i.imgur.com/QbzmJlE.jpg">,
      'pink': <img src="..."> 
    }
    

    And later, when you draw the image:

    if (images.hasOwnProperty(radioValue)) {
      var image = images[radioValue];
      canvas.getContext('2d').drawImage(image, 0, 0);
    } else {
      // the image doesn't exist
    }