ScottRookie ScottRookie - 17 days ago 6
jQuery Question

Display image above the shape at Canvas

I'm creating a website that was able to display shapes and colors in the canvas, my problem is the picture won't show up anymore.

Here's my html sample:

// These are my choices for the first step in designing.
<input type="radio" id="shape_1" name="shape" onchange="display()" /> circle
<input type="radio" id="shape_2" name="shape" onchange="display()" /> rectangle
//2nd step, choose color
<input type="radio" id="color_1" name="color" onchange="display()" /> RED
//3rd step, choose image
<select name="picture" id="picture_display" onchange="display()" />
<option value="apple">Apple</option>
<option value="orange">Orange</option>

<canvas id="displaycanvas" height="450px" width="820px" style="position:absolute;"> </canvas>


for my JS (separate):

function display() { //working fine
var canvas = document.getElementById('displaycanvas');
context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);

function Choices() { //working fine too...
if (document.getElementById('color_1').checked) {
context.strokeStyle = "#FF0000";
}
if (document.getElementById('shape_1').checked) {
context.beginPath();
context.arc(95, 50, 40, 0, 2 * Math.PI);
context.stroke();
}
if (document.getElementById('shape_2').checked) {
context.beginPath();
context.rect(50, 27, 50, 100);
context.stroke();
}
}

function Picture() { //these part it won't work, I've tried to do something like this.
if (document.getElementById('picture_display').value == 'apple') {
document.getElementById('displaycanvas').src = 'http://www.logospike.com/wp-content/uploads/2015/12/Apple_Logo_Png_04.png';
}
if (document.getElementById('picture_display').value == 'orange') {
document.getElementById('displaycanvas').src = 'http://dailyrindblog.com/styleguide/web_version/logo_fruit.png';
}
}
}


I want the image will be above for the first 2 steps but doesn't go beyond either those given shapes (if possible, if its not it's fine). Anything I simply missed or change it all? Thank you so much in advance!

For the dragging code you can suggest some links that is applicable to this one.

Answer

You have to get a reference to the context, then load image object and when done draw the image on the context

function Picture() { 
      var e = document.getElementById("picture_display");
      var selValue1 = e.options[e.selectedIndex].value;

      var context = document.getElementById('displaycanvas').getContext('2d');
      var imageObj = new Image();
      imageObj.onload = function() {
        context.drawImage(imageObj, 0, 0);
      };

    if (selValue1 === 'apple') {
      imageObj.src = 'http://www.logospike.com/wp-content/uploads/2015/12/Apple_Logo_Png_04.png';
    }
    if (selValue1 === 'orange') {
      imageObj.src = 'http://dailyrindblog.com/styleguide/web_version/logo_fruit.png';
    }
  }
Comments