将已上传的图像(使用Ajax)绘制到画布 [英] Drawing Uploaded Image(with Ajax) to Canvas

查看:139
本文介绍了将已上传的图像(使用Ajax)绘制到画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery AJAX Form插件来上传图片,而不刷新页面。如果我在图片标签中显示上传的图片(将src设置为上传的图片路径),则可以。但是,我无法在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); }

上面是我在Ajax进程调用时的回调函数。非常感谢您的帮助。

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

更新:完整代码

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


推荐答案

对图像的自动请求?

如同将updateSrc设为

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

    }

其中imagePath是映像文件的路径。
例如:

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

updateSrc(images / example_image.jpg);

updateSrc("images/example_image.jpg");

ajax请求甚至不需要写入。

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

这篇关于将已上传的图像(使用Ajax)绘制到画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆