Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing Uploaded Image(with Ajax) to Canvas

I am using jQuery AJAX Form plugin to upload images without refreshing the page. It is ok if I show the uploaded image within an image tag( setting src to uploaded image path.) However, I cannot draw that uploaded image on a canvas element. I actually do not know what the problem is.

if (isset($_FILES["image"]["name"]) && !empty($_FILES["image"]["name"])) {
  $filename = $_FILES["image"]["name"];
  $tmpname = $_FILES["image"]["tmp_name"];

  $location = "uploads/";
  move_uploaded_file($tmpname, $location.$filename);
  echo $location.$filename;
} else {}​

var canvas = document.getElementById("canv");
var contex = canvas.getContext("2d");           
var img = new Image();
img.src = responseText;
img.onload = function(){ contex.putImageData(img, 0, 0); }

Above is my callback function(inside) when I call when the Ajax process is done. Thanks for any helpful answer.

UPDATE: FULL CODE

<html>
<head>
<script src="jq171.js"></script>  <!--jQuery-->
<script src="jqform.js"></script> <!--jQuery ajax Form plugin-->

<script>
    $(document).ready(function(){
        $("#myform").ajaxForm(function({success: updateSrc}){
        });
    });

    function updateSrc(responseText){
        var canvas = document.getElementById("canv");
        var contex = canvas.getContext("2d");

        var img = new Image();
        img.src = responseText;
        img.onload = function(){ contex.drawImage(img, 0, 0); }

    }
</script>
</head>
<body>
<form id="myform" action="this.php" method="post" enctype="multipart/form-data" >
<canvas id="canv" width="400px" height="400px"></canvas>
<input type="file" name="image"/>
<input type="submit"/>
</form>
</body>
</html>
like image 691
msharpp Avatar asked Dec 03 '25 15:12

msharpp


1 Answers

Is there a reason why you don't just do an automatic request for the image?

As in leave the updateSrc as

function updateSrc(imagePath){
        var canvas = document.getElementById("canv");
        var contex = canvas.getContext("2d");

        var img = new Image();
        img.src = imagePath;
        img.onload = function(){ contex.drawImage(img, 0, 0); }

    }

Where the imagePath is the path to the image file. for example:

updateSrc("images/example_image.jpg");

So jquery ajax request doesn't even need to be written.

like image 146
aaronrmm Avatar answered Dec 06 '25 07:12

aaronrmm