clear Canvas and save Canvas

2019-06-03 16:37发布

问题:

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

回答1:

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.