简体   繁体   中英

clear Canvas and save Canvas

I am just finishing web application for picture analysis and inpainting. And I need help with canvas. This is what I do:

EDIT:

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

But now I have problem with clearCanvas function. Because browsers cannot read property 'width'. This is my full source code. How, please can someone tell my what I doing wrong.

EDIT:

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

I need to save canvas as jpeg image on local disk after user click 'save image'. That's mean, areas which are transparent in canvas become black background.

I need something like this: http://i48.tinypic.com/2w5vhpv.jpg

You can save the canvas to an image file with the canvas.toDataUrl('image/jpg') .

Regarding the first question: normally you clear the canvas with context.clearRect(0, 0, canvas.width, canvas.height) method. That being said, your code should work as expected if the canvas and context declarations have been made correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM