2016-11-18 86 views
0

我創建了一個能夠在畫布上顯示形狀和顏色的網站,我的問題是圖片不會再顯示出來。顯示圖像上方的形狀在畫布上

這裏是我的HTML樣本:

// 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> 

我的JS(獨立):

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'; 
    } 
    } 
} 

我想要的圖像將高於前2個步驟,但沒有超越任何那些給定形狀(如果可能,如果它不是很好)。任何我只是錯過或改變這一切? 非常感謝你提前!

對於拖動代碼你可以建議一些適用於此的鏈接。

+0

你有像[檢查您的控制檯?(http://stackoverflow.com/文檔/ javascript/185 /開始與JavaScript/714 /使用控制檯日誌) –

+0

是的,但沒有。它只是工作正常,但不顯示圖像。 – Poofbrayy

回答

1

你必須去的上下文的引用,然後加載圖像對象,當完成繪製上下文

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'; 
    } 
    } 
+0

感謝您的更新!最後它的作品!謝謝! – Poofbrayy