2012-07-27 131 views
1

我只是完成圖像分析和修補的Web應用程序。我需要畫布的幫助。這是我做的:清除畫布和保存畫布

編輯:

<img id="imgEdit" src="<?php echo $imagename; ?>" border="0"> 
    <canvas id="canvasPaint" 
     width="<?php echo $width; ?>" 
     height="<?php echo $height; ?>"> 
    </canvas> 
    <input type="button" value="Clear" onClick="clearCanvas();" class="button"> 
<input type="button" value="Save" onClick="saveViaAJAX();" class="button"> 
    <div id="debugFilenameConsole">Wait for a while after clicking the button and the filename of the image will be shown to you. </div> 

但現在我有clearCanvas功能問題。因爲瀏覽器無法讀取屬性'寬度'。這是我的完整源代碼。怎麼樣,請有人告訴我我做錯了什麼。

編輯:

function clearCanvas() 
       { 
       var theCanvas = document.getElementById("canvasPaint"); 
       if (theCanvas && theCanvas.getContext) { 
        var ctx = theCanvas.getContext("2d"); 
        if (ctx) { 

        ctx.clearRect(0, 0, <?php echo $width; ?>, <?php echo $height; ?>); 

        var srcImg = document.getElementById("imgEdit"); 
        ctx.drawImage(srcImg, 0,0); 

        clickX = new Array(); 
        clickY = new Array(); 
        clickDrag = new Array(); 
       }}} 
function saveViaAJAX() 
{ 
    var theCanvas = document.getElementById("canvasPaint"); 
    var canvasData = theCanvas.toDataURL("image/jpg"); 
    var postData = "canvasData="+canvasData; 

    var ajax = new XMLHttpRequest(); 
    ajax.open("POST",'canvasSave.php',true);  
    ajax.setRequestHeader('Content-Type', 'canvas/upload'); 

    ajax.send(postData); 
} 

我需要保存畫布在本地磁盤上的JPEG圖像用戶之後點擊「保存形象」。這意味着,畫布上透明的區域會變成黑色背景。

我需要的是這樣的: http://i48.tinypic.com/2w5vhpv.jpg

+0

你可以發佈'ctx'和'canvas'的聲明,以及它們相對於'clearCanvas'聲明的位置嗎? – 2012-07-27 18:11:36

+0

同時使用'clearRect'和'width'是多餘的。也就是說,'canvas'的價值是什麼? – pimvdb 2012-07-27 18:20:22

+0

我解決了我的問題。我編輯我的帖子並提供源代碼。 – Rile 2012-08-02 15:19:59

回答

0

可以在畫布保存到與canvas.toDataUrl('image/jpg')的圖像文件。

關於第一個問題:通常你用context.clearRect(0, 0, canvas.width, canvas.height)方法清除畫布。也就是說,如果canvas和上下文聲明已經正確完成,那麼你的代碼應該按照預期工作。

+0

函數clearCanvas()和函數saveViaAJAX()不起作用。你能幫我麼? – Rile 2012-07-28 13:36:25