保存 html 画布图像 [英] Save a html canvas image

查看:30
本文介绍了保存 html 画布图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题可能已经有了答案,但我还没有找到答案,而且我的项目有一个截止日期.

I know there is probably an answer already to this question but I haven't been able to find it yet and there is a deadline on my project.

所以我制作了一个 html5 画布,我希望能够用一个(或多个)按钮做两件事.我希望用户能够通过单击保存按钮来保存他刚刚所做的事情,理想情况下我希望下载图像(而不是必须右键单击和将图像另存为".这就是我到目前为止已经能够做到).我还希望保存图像(可能保存到数据库?或服务器?我不知道它是如何工作的),以便绘图的一部分(或全部,取决于代码的难度)之前已经完成,下次其他人登录时使用(不一定是同一人,同一个IP).这可能吗?

So I have made an html5 canvas and I would like to be able to do two things with one(or more) buttons. I would like the user to be able to save what he has just done by clicking on the save button and ideally I would like the image to be downloaded (as opposed to having to right click and "Save image as". This is what I have been able to do so far). I would also like the image to be saved (maybe to a database? or a server? I don't know how it works) so that a part of the drawing (or all of it, depending on the difficulty of the code) that has been done before is used the next time someone else logs on (not necessarily the same person with the same IP). Is this possible?

我对代码和自学非常陌生,因此对代码的任何额外评论以帮助我理解都会受到额外的赞赏.

I am very new to code and self teaching myself so any extra comments on the code to help me understand would be extra-appreciated.

推荐答案

关于第一个任务,可以通过canvas支持的toDataUrl方法将canvas内容导出为图片代码>对象.

Regarding the first task, you can export the canvas content to an image with toDataUrl method supported by the canvas object.

var canvas = document.getElementById("canvas");
if (canvas.getContext) {
    var ctx = canvas.getContext("2d");                // Get the context for the canvas.
    var myImage = canvas.toDataURL("image/png");      // Get the data as an image.
}

var image = document.getElementById("image");  // Get the image object.
image.src = myImage; 

关于第二个任务,将画布保存到图像后,您可以使用 ajax 调用将结果图像上传到数据库中.这是一个如何使用它的简单示例:

As regarding the second task, after you saved the canvas to an image you can upload the resulted image into the database by using an ajax call. Here is a simple example for how to use it:

$.ajax({  
        url: "upload.php",  
        type: "POST",  
        data: formdata,  
        processData: false,  
        contentType: false,  
        success: function (res) {  
            document.getElementById("response").innerHTML = res;  
        }  
    });

有关完整示例,请参阅以下文章:

For a full example see these articles:

http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/

http://coursesweb.net/ajax/upload-images

这篇关于保存 html 画布图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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