文章源自:http://simeonvisser.hubpages.com/hub/HTML5-Tutorial-How-To-Use-Canvas-toDataURL
HTML5 Tutorial: How to Get and Set a Base64 Image on Canvas using toDataURL
For many web applications it can be useful to turn the visual image on a HTML5 canvas into a base64 representation of it which can be sent and shared. As this tutorial will show you, that is not very difficult and it is also very simple to load a base64 image onto a HTML5 canvas. The method toDataURL() of a canvas plays an important role in this process and I'll show you how to use it.
In this tutorial you'll see both techniques for converting an image to base64 and how to go from base64 to an image. I'll also discuss some possible ways this functionality can be used in interactive websites.
How about a website where you can share your own images with others - such functionality is easily implemented with the techniques described in this tutorial. I will give several other examples later in this tutorial.
What is the HTML5 canvas?
The HTML5 canvas is one of my favorite additions to the HTML web standard. With it you can write some JavaScript code to draw directly on your webpages. I have written several tutorials that explain the basics of how to draw on a canvas and how to do various things, like creating text, circles and arcs:
-
HTML5 Tutorial: Basics of Canvas Drawing
In this tutorial I'm going to demonstrate how to use the canvas element in HTML5 to draw colorful graphics for your website. The tutorial features two rich examples which are explained step by step. -
HTML5 Tutorial: Text Drawing with Fancy Colors and Effects
You can do much more than just drawing text in HTML5! In this tutorial I'll show various effects to make some fancy texts, including shadows, gradients and rotation. -
HTML5 Tutorial: Drawing Circles and Arcs on Canvas
Drawing circles and arcs in HTML5 can be quite a challenge. In this tutorial I explain how to draw circles and arcs and how the angles of arcs are measured. This tutorial contains many examples.
What is base64?
Base64 is a way of representing data using only readable characters like letters, numbers and some symbols like the plus symbol. This data can be anything, like an image or a file, but commonly it is data that is not plain text (otherwise there is not much point in converting it to base64, is there?).
This representation, also known as a base64 string, is very useful because it can be used anywhere that normal text can also be used. It makes it easier to store the images - you can have several images in a plain text file for example.
The exact details of how base64 works are not relevant for this tutorial. All that matters is that base64 is a different way of representing the same visual image data but in a textual way. I'll refer the interested reader to the base64 article on Wikipedia if you want to know more.
How to get canvas image data using toDataURL()
The canvas in HTML5 has a method called toDataURL() that you can call to turn a HTML5 canvas into a PNG image and to get the image data of that canvas. By default it will give you a base64 representation of the image in PNG format. In simpler terms: you will get a PNG image but it has been encoded in base64. For the toDataURL() method, the PNG format is the only image format that is supported by all HTML5-compliant web browsers. Some browsers support multiple image formats.
You can call toDataURL with an argument, such as "image/jpeg" or "image/png" if you want to specify which image format you want. We don't need to worry about this and we can simply call toDataURL without arguments to get a PNG image in base64 representation. Be aware that the HTML5 standard only requires browsers to support PNG for toDataURL so it is best to use that image format if you want to make your code work in all web browsers.
In the following code we have a canvas and we are calling the toDataURL() method to get the image data:
<canvas id="mycanvas" width="300" height="300"> </canvas> <script type="text/javascript"> var canvas = document.getElementById('mycanvas'); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.arc(100, 100, 50, 1.5 * Math.PI, 0.5 * Math.PI, false); ctx.lineWidth = 10; ctx.stroke(); var imgData = canvas.toDataURL(); </script>
The variable imgData now contains a base64 representation of the image currently on the canvas. It looks something like this: data:image/png;base64,iVBORw0 ... AAAElFTkSuQmCC. I have only shown the beginning and the end of the data because it would be too much to show it all. As you can see it starts with "data:", then the image type ("image/png"), then the encoding ("base64") and finally all the data of the image in text.
Simply by calling toDataURL() we have turned the image into a textual representation. That's a good thing because text is a lot easier to share or to send. In fact, if you were to copy this whole textual representation of the image and you would send it to someone else, they can paste it into the address bar of their browser and they will see the image.
What can we do with toDataURL()?
What can we do with this data?
- We could send the base64 string to the server for storage in a database. A user could create an image, using a HTML5 canvas image editor, and the image could be submitted to the website. The image could be stored as base64 string in the database and it can easily be loaded and displayed on a canvas again (see later in this tutorial on how to do this). People could create and shart art this way.
- We can create undo / redo functionality for such a canvas image editor. You could keep track of all the edits that the user does and you could save every version of the image as a base64 string. If the user made a mistake and wants to undo the most recent edit then you can load the latest base64 and show it on the canvas.
- A "send image by email" functionality. As you may or may not know, base64 is also used when you attach an image (or any file for that matter) to an email. A website could now offer the ability to send an image to your friends by email. It simply receives the image from you in base64 representation and then it composes an email with that base64 data included.
How to load base64 image data on a HTML5 canvas
You now also want to do the reverse: if you have a base64 representation of an image, how can we load that base64 image data onto a HTML5 canvas? This is not difficult because we can simply create an Image, assign the data to that image and then draw the image. Here is the JavaScript code to do just that:
var myImage = new Image(); myImage.src = imgData; ctx.drawImage(myImage, 0, 0);
The variable imgData contains the base64 image data. If the canvas was previously empty, you will now see our image once more on the canvas. After that you can use toDataURL() again to get the data in base64 representation.
Conclusion
In this tutorial we have seen how to take the image that is displayed on a HTML5 canvas, how to turn it into a base64 string and how to do the reverse: we have seen how to load a base64 image on a HTML5 canvas. What you do with those base64 strings is totally up to you!
Good luck with your web development projects and happy coding!
相关推荐
1. **颜色空间转换**:OpenCV支持多种颜色空间的转换,如BGR to Gray,RGB to HSV等。 2. **图像滤波**:包括均值滤波、高斯滤波、中值滤波等,用于平滑图像或去除噪声。 3. **边缘检测**:Canny、Sobel、Laplacian...
graph slam tutorial :从推导到应用3(g2o版程序),包含文档读取,及后端优化
You'll learn how to turn your web pages into compelling iPhone web apps using WebKit, iUI, and Canvas. The authors also take you step by step into more complex Objective-C programming. They help you ...
Analog Circuit Design Volume 1 - A tutorial guide to applications and solutions password: goCHINAgo!
在这个"FMC-IMAGEON - Building a Video Design from Scratch Tutorial"中,我们将会深入探讨如何从零开始构建一个视频设计项目。教程的标题暗示了这是一次全面的学习过程,旨在帮助用户掌握视频设计的基础知识和...
Tutorial 2: Creating a Framework and Window Tutorial 3: Initializing DirectX 11 Tutorial 4: Buffers, Shaders, and HLSL Tutorial 5: Texturing Tutorial 6: Diffuse Lighting Tutorial 7: 3D...
《SLAM入门教程:A Tutorial Approach to Simultaneous Localization and Mapping》是一本为初学者设计的教程,旨在帮助读者从零基础开始理解SLAM的基本原理和方法。书名“SLAM for Dummies”暗示了它以通俗易懂的...
Serving as a tutorial and reference, this comprehensive resource explains the basic structure and necessary formatting to create a static (non-changing) and dynamic (changing) page on the Internet. ...
Alex Smola et al.A tutorial on support vector regression.Statistics and Computing,2004 In this tutorial we give an overview of the basic ideas underlying Support Vector (SV) machines for function ...
本书教您如何使用Ruby on Rails开发和部署真正的,具有工业实力的Web应用程序,Ruby on Rails是为诸如Twitter,Hulu,GitHub和Yellow Pages等顶级网站提供支持的开源Web框架。
The C++ Standard Library: A Tutorial and Reference, Second Edition, describes this library as now incorporated into the new ANSI/ISO C++ language standard (C++11). The book provides comprehensive ...
##### 5. **安全性** - **Java EE安全模型**:涵盖了认证、授权、角色映射等功能,确保了应用的安全性。 ##### 6. **上下文与依赖注入** - **Contexts and Dependency Injection (CDI)**:提供了上下文管理和依赖...
C# Design Patterns: A Tutorial is a practical guide to writing C# programs using the most common patterns. This tutorial begins with clear and concise introductions to C#, object-oriented ...
4. **序列到序列模型(Sequence-to-Sequence, Seq2Seq)**:结合CNN和RNN,形成一个Seq2Seq模型,将图像特征编码为固定长度的向量,然后解码生成文本。 5. **损失函数(Cross-Entropy Loss)**:在训练过程中,通常使用...
"51CTO下载-HTML5 Tutorial - 41 - Saving and Restoring the Canvas"这一主题主要讲解的是如何在Canvas上保存和恢复绘制的状态,这对于创建复杂的交互式图形或者动画场景至关重要。 Canvas API提供了两个关键方法...
- **Canvas to Image**:使用`toDataURL()`方法将Canvas内容转换为图像数据URL,然后可以下载或分享。 - **Android集成**:将生成的图像数据URL发送回Java层,可以保存到设备或者上传到服务器。 6. **最佳实践和...
This is a BETA release of the "print friendly" version of the Linux Knowledge Base and Tutorial. Here are a few things to note: Due to technical problems, this version does not contain the chapter on ...
Understanding .NET - A Tutorial and Analysis Understanding .NET - A Tutorial and Analysis Understanding .NET - A Tutorial and Analysis