ScottRookie ScottRookie - 1 year ago 57
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.arc(95, 50, 40, 0, 2 * Math.PI);
if (document.getElementById('shape_2').checked) {
context.rect(50, 27, 50, 100);

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 = '';
if (document.getElementById('picture_display').value == 'orange') {
document.getElementById('displaycanvas').src = '';

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 Source

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 = '';
    if (selValue1 === 'orange') {
      imageObj.src = '';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download