Home Web Front-end JS Tutorial The toDataURL() method in canvas converts images to dataURL (base64)

The toDataURL() method in canvas converts images to dataURL (base64)

Jan 18, 2018 am 10:15 AM
canvas

This article mainly introduces to you the relevant information about using toDataURL() in canvas to convert images into dataURL(base64). The article introduces it in detail through sample code, which has certain reference learning value for everyone's study or work. Friends who need it, please follow the editor to learn together. I hope it can help everyone.

Benefits of converting images to base64

Converting images to Base64 encoding allows you to easily insert images into other web pages and editors without uploading files. This is extremely convenient for some small pictures, because you don't need to find a place to save the picture.

Convert the image to base64 encoding, which is generally used for small images on the web. It can not only reduce the number of image requests (collected into js and css codes), but also prevent problems such as relative paths. Resulting in a 404 error for the image.

Introduction

Assume an application scenario: Due to some special reasons, the image path is requested from the server, and the base64 dataURL of the corresponding image is required to be obtained through this path. In this scenario, we first infer that the image path is accessible, and we also need a way to convert the image to a dataURL.

How do we achieve it?

dataURL

Let’s briefly review the syntax of the orthodox dataURL, which will help us check whether the converted content is correct. A complete dataURI should look like this:

data:[<mediatype>][;base64],<data>
Copy after login

The mediatype declares the file type, following MIME rules, such as "image/png", "text/plain"; followed by the encoding type, here we only cover base64 ;The next step is the encoded content of the file. We often see the src of the img tag in HTML written like this:

src="data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAwAAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFzByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSpa/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJlZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uisF81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PHhhx4dbgYKAAA7"
Copy after login

This img refers to the dataURL encoded in base64. As long as the browser supports it, it can be decoded into a gif image and rendered.

.toDataURL()

The FileReader object also has similar methods, such as .readAsDataURL(), but it only accepts file or blob types, and these two types can generally only be passed through Get the files attribute of the element, or use the Blob() constructor to manually create a new object. The embarrassing thing is that we currently only have the image path, which is subject to the browser's security policy. The files attribute of is read-only, and the Blob() constructor only accepts file content. Both methods are It cannot be obtained directly through the image path. The hypothetical application scenario above forces us to first consider how to obtain the image content through the path. is OK and can be drawn into , and happens to have the .toDataURL() method.

Everything is ready, we only need to put the image obtained by into and then convert it through the .toDataURL() method to get the base64-encoded dataURL. Let’s look at the syntax of this method:

canvas.toDataURL([type, encoderOptions]);
Copy after login

canvas is the DOM element object; the parameter type specifies the image type. If the specified type is not supported, it will be replaced by the default value image/png; encoderOptions can be image Set the image quality for /jpeg or image/webp type pictures, with a value of 0-1. If it exceeds the value, it will be replaced by the default value of 0.92.

It should be noted that before converting to dataURL, you must first ensure that the image is successfully loaded, so the .toDataURL() method should be written in the onload asynchronous event of . Now let’s implement a functional function:

 function getBase64(url){
  //通过构造函数来创建的 img 实例,在赋予 src 值后就会立刻下载图片,相比 createElement() 创建 <img> 省去了 append(),也就避免了文档冗余和污染
  var Img = new Image(),
   dataURL='';
  Img.src=url;
  Img.onload=function(){ //要先确保图片完整获取到,这是个异步事件
   var canvas = document.createElement("canvas"), //创建canvas元素
    width=Img.width, //确保canvas的尺寸和图片一样
    height=Img.height;
   canvas.width=width;
   canvas.height=height;
   canvas.getContext("2d").drawImage(Img,0,0,width,height); //将图片绘制到canvas中
   dataURL=canvas.toDataURL('image/jpeg'); //转换图片为dataURL
  };
 }
Copy after login

A conversion function that can be called at any time is completed. It will return an entire dataURL string after the image is loaded.

Improvement

The onload event ensures that the conversion task is executed after loading, but it brings a new problem - the dataURL will only be returned after the image is loaded, and we cannot determine when the image is loaded. Complete loading. If the dataURL needs to be processed later (such as passing it to other servers), it is necessary to add a callback. This can ensure that the subsequent processing task is executed after the dataURL is successfully obtained. We need to modify getBase64():

 function getBase64(url,callback){ //添加一个回调参数
  ...
  Img.onload=function(){
   ...
   canvas.getContext("2d").drawImage(Img,0,0,width,height);
   dataURL=canvas.toDataURL('image/jpeg');
   callback?callback(dataURL):null; //调用回调函数
  };
 }
Copy after login

Add callback during execution:

 getBase64('//upload.jianshu.io/users/upload_avatars/555630/fdd1b798e6b0.jpg',(dataURL)=>{
  console.log(dataURL);
 });
Copy after login

That’s it. If compatibility is not considered, maybe we can use promises and generators to implement it, and it will be more perfect if we add some error handling.

Related recommendations:

html5 Canvas realizes image rotation

jquery plug-in canvaspercent.js realizes the percentage round cake effect example sharing

How Canvas handles images

The above is the detailed content of The toDataURL() method in canvas converts images to dataURL (base64). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Which schools use canvas? Which schools use canvas? Aug 18, 2023 pm 05:59 PM

Schools using canvas include Stanford University, MIT, Columbia University, University of California, Berkeley, etc. Detailed introduction: 1. Stanford University uses Canvas as its main online learning platform. Teachers and students at Stanford University use Canvas to manage and communicate course content, and learn through functions such as online discussions, assignment submissions, and exams; 2. Ma Provincial Polytechnic Institute and MIT also use Canvas as their online learning management system and conduct course management through the Canvas platform; 3. Columbia University, etc.

What are the canvas arrow plug-ins? What are the canvas arrow plug-ins? Aug 21, 2023 pm 02:14 PM

The canvas arrow plug-ins include: 1. Fabric.js, which has a simple and easy-to-use API and can create custom arrow effects; 2. Konva.js, which provides the function of drawing arrows and can create various arrow styles; 3. Pixi.js , which provides rich graphics processing functions and can achieve various arrow effects; 4. Two.js, which can easily create and control arrow styles and animations; 5. Arrow.js, which can create various arrow effects; 6. Rough .js, you can create hand-drawn arrows, etc.

What are the details of the canvas clock? What are the details of the canvas clock? Aug 21, 2023 pm 05:07 PM

The details of the canvas clock include clock appearance, tick marks, digital clock, hour, minute and second hands, center point, animation effects, other styles, etc. Detailed introduction: 1. Clock appearance, you can use Canvas to draw a circular dial as the appearance of the clock, and you can set the size, color, border and other styles of the dial; 2. Scale lines, draw scale lines on the dial to represent hours or minutes. Position; 3. Digital clock, you can draw a digital clock on the dial to indicate the current hour and minute; 4. Hour hand, minute hand, second hand, etc.

What versions of html2canvas are there? What versions of html2canvas are there? Aug 22, 2023 pm 05:58 PM

The versions of html2canvas include html2canvas v0.x, html2canvas v1.x, etc. Detailed introduction: 1. html2canvas v0.x, which is an early version of html2canvas. The latest stable version is v0.5.0-alpha1. It is a mature version that has been widely used and verified in many projects; 2. html2canvas v1.x, this is a new version of html2canvas.

Learn the canvas framework and explain the commonly used canvas framework in detail Learn the canvas framework and explain the commonly used canvas framework in detail Jan 17, 2024 am 11:03 AM

Explore the Canvas framework: To understand what are the commonly used Canvas frameworks, specific code examples are required. Introduction: Canvas is a drawing API provided in HTML5, through which we can achieve rich graphics and animation effects. In order to improve the efficiency and convenience of drawing, many developers have developed different Canvas frameworks. This article will introduce some commonly used Canvas frameworks and provide specific code examples to help readers gain a deeper understanding of how to use these frameworks. 1. EaselJS framework Ea

uniapp implements how to use canvas to draw charts and animation effects uniapp implements how to use canvas to draw charts and animation effects Oct 18, 2023 am 10:42 AM

How to use canvas to draw charts and animation effects in uniapp requires specific code examples 1. Introduction With the popularity of mobile devices, more and more applications need to display various charts and animation effects on the mobile terminal. As a cross-platform development framework based on Vue.js, uniapp provides the ability to use canvas to draw charts and animation effects. This article will introduce how uniapp uses canvas to achieve chart and animation effects, and give specific code examples. 2. canvas

What properties does tkinter canvas have? What properties does tkinter canvas have? Aug 21, 2023 pm 05:46 PM

The tkinter canvas attributes include bg, bd, relief, width, height, cursor, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertwidth, selectbackground, selectforeground, xscrollcommand attributes, etc. Detailed introduction

Explore the powerful role and application of canvas in game development Explore the powerful role and application of canvas in game development Jan 17, 2024 am 11:00 AM

Understand the power and application of canvas in game development Overview: With the rapid development of Internet technology, web games are becoming more and more popular among players. As an important part of web game development, canvas technology has gradually emerged in game development, showing its powerful power and application. This article will introduce the potential of canvas in game development and demonstrate its application through specific code examples. 1. Introduction to canvas technology Canvas is a new element in HTML5, which allows us to use

See all articles