msharpp
msharpp

Reputation: 479

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>

Upvotes: 3

Views: 3663

Answers (2)

aaronrmm
aaronrmm

Reputation: 491

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.

Upvotes: 1

jazzytomato
jazzytomato

Reputation: 7214

You are using wrong function.

context.putImageData(imgData,x,y);

it takes image data, which is not an image object but raw pixel data. Instead, you want to use :

context.drawImage(img,0,0);

It should solve your problem

Upvotes: 0

Related Questions