SlideShare ist ein Scribd-Unternehmen logo
1 von 3
HTML5 Canvas – toDataURL()
support for Android devices –
working Phonegap 2.2.0 Plugin

Actual blog post link - http://jbkflex.wordpress.com/2012/12/21/html5-canvas-todataurl-support-
for-android-devices-working-phonegap-2-2-0-plugin/

I have been working on a Phonegap based Android app which involves the HTML5 Canvas. So this is
what I had been trying for some time – get a png/jpeg image of the Canvas (its a Canvas paint app,
something like this and I want to get an image of the drawing..) and then upload the image to Facebook
on a user’s album. Let me tell you, it has been a heck of a task and around 15-20 days of restlessness.
The problem stood tall when I discovered that for Android 2.3 (in general Android < 4.0) devices the
native HTML5 Canvas- toDataURL() function does not work, which would otherwise give a base64
encoded string as image data which then can be used as a source for a HTML <img /> tag. It was
working for 4.0 devices as I tested it on a Samsung Galaxy S3 and a Samsung Tab. Hence I Goggled a
bit and found out various people had this issue before. So it seemed that older Android web-kits (a
Phonegap app runs on the Android webview which is actually the webkit browser inside a native wrapper)
does not support that native method of converting a Canvas to an image through toDataURL() generated
base64 encoded strings. Guess what I had todo? I had to go for a custom Phonegap plugin as there
was no other way. This is how I thought of implementing it – pass the canvas object from javascript side
to the Phonegap plugin’s Java class and somehow get the base64 encoded string of the Canvas and
return it back to javascript as the callback parameter. This is what the native toDataURL() method actually
does – convert the Canvas to a base64 encoded image data string.
Not being a Java developer, I had to look for external help, that’s where I came across Ryan Gillespie’s
plugin which he developed some time back for the very purpose that I was looking for. But the code was
kinda old and is not compatible with Phonegap 2.2.0 (this is the version that I am using for development)
as there have been numerous changes in the Phonegap’s plugin architecture. I had to do some
modifications to the code – mainly on the Java side. I used Ryan’s Java code and modified it a little bit. I
wrote the javascript interface of the plugin entirely. Overall, thanks to Ryan for doing the tough part and its
been possible to achieve the task. I had the modified plugin running successfully on older Android’s with
Phonegap 2.2.0 and returning a valid base64 encoded image string of the HTML5 Canvas.
Let’s quickly talk on the changes that I made. I will not discus on how to create custom Phonegap plugins
in this post. For that you need to checkout the official documentation. It is better if you have some idea of
creating custom plugins and what goes into creating a plugin, specifically the communication between
JavaScript and Java.
As I said earlier I modified Ryan’s Java class – CanvasPlugin.java. Download the file and check out the
source. You will notice that the main changes are the new format for the overridden execute() method
and it returns a boolean type now, also your plugin class should now extend the CordovaPlugin
superclass, the third major change being the way callbackContext object now calls the success and error
methods and in a way calls the javascript interface after the execute() method has finished it’s execution.
There’s once more important change that I made is inside the custom getImageData() method –
Base64.encodeBase64() has now been deprecated for the android.util.Base64 class, instead use
Base64.encodeToString() method. So, mostly these changes made the Java class compatible with
Phonegap 2.2.0. Now let’s check out the new JavaScript interface for the plugin.
I did not use Ryan’s javascript file. I wrote a simple one myself. So get a copy of it first –
CanvasPlugin.js. The logic is simple if you know how to write a javascript part of a Phonegap plugin. I
am creating a canvasplugin method and exposing it to the global window object so that it is accessible
across your code. The canvasplugin method takes two parameters – the HTML5 Canvas reference and
the callback function reference which will be called once we have a result from Java side. Next important
thing is calling the CanvasPlugin.java execute() method and passing it the right arguments. For that I
would again suggest to go through the official documentation. You can modify the javascript code to
make it better probably.
With both the files ready, let’s see how to use it and get it working. Firstly you have to add these two files
to your Phonegap Android project. Add the CanvasPlugin.js file inside assets/www/ folder and provide a
reference to it in your index.html file, like this


<script type="text/javascript" charset="utf-8"
src="CanvasPlugin.js"></script>


Then create a directory inside your project’s src folder that matches the package name of
CanvasPlugin.java class. For our case make a directory – /org/apache/cordova/plugin inside src and then
paste CanvasPlugin.java inside it. If you change the package name, make sure to change the directory
structure as well. The package name can be found at the top of CanvasPlugin.java file.


Next thing to do is to register the plugin in the config file – open res/xml/config.xml and then add the
plugin details given below to the <plugins></plugins> section of the XML file. The name attribute is the
Java class name and the value is the path of the class. This should match the package name.


<plugin name="CanvasPlugin" value="org.apache.cordova.plugin.CanvasPlugin"/>


And then call the plugin inside your javascript (your script.js file or so) code like this. (You can call this
inside a button click handler or so),


var canvas = document.getElementById("myCanvas");
window.canvasplugin(canvas,function(val){


  document.getElementById("myImg").src = val.data;


});


where myCanvas is the ID of the HTML Canvas. The callback function receives the Base64 encode
image string inside the data property of the returned value. Make sure to access it through val.data. Now
you can use this as a source for an HTML image tag and you can get a preview image of your canvas.
Here I am getting a Base64 encoded .png image string. If you need to change the mimeType, you can do
that inside the CanvasPlugin.js file. Also you can pass that as a parameter to the javascript interface
rather than hard code inside the CanvasPlugin.js file (which I did mistakenly). So pass it from your
script.js to window.canvasplugin() call along with the canvas reference and the callback reference, as the
third parameter.
Lot of writing and English!! DOH!! But the cool plugin architecture has been able to overcome the
shortcomings isn’t it.

Weitere ähnliche Inhalte

Kürzlich hochgeladen

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 

Empfohlen

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Empfohlen (20)

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 

HTML5 Canvas – toDataURL() support for Android devices – working Phonegap 2.2.0 Plugin

  • 1. HTML5 Canvas – toDataURL() support for Android devices – working Phonegap 2.2.0 Plugin Actual blog post link - http://jbkflex.wordpress.com/2012/12/21/html5-canvas-todataurl-support- for-android-devices-working-phonegap-2-2-0-plugin/ I have been working on a Phonegap based Android app which involves the HTML5 Canvas. So this is what I had been trying for some time – get a png/jpeg image of the Canvas (its a Canvas paint app, something like this and I want to get an image of the drawing..) and then upload the image to Facebook on a user’s album. Let me tell you, it has been a heck of a task and around 15-20 days of restlessness. The problem stood tall when I discovered that for Android 2.3 (in general Android < 4.0) devices the native HTML5 Canvas- toDataURL() function does not work, which would otherwise give a base64 encoded string as image data which then can be used as a source for a HTML <img /> tag. It was working for 4.0 devices as I tested it on a Samsung Galaxy S3 and a Samsung Tab. Hence I Goggled a bit and found out various people had this issue before. So it seemed that older Android web-kits (a Phonegap app runs on the Android webview which is actually the webkit browser inside a native wrapper) does not support that native method of converting a Canvas to an image through toDataURL() generated base64 encoded strings. Guess what I had todo? I had to go for a custom Phonegap plugin as there was no other way. This is how I thought of implementing it – pass the canvas object from javascript side to the Phonegap plugin’s Java class and somehow get the base64 encoded string of the Canvas and return it back to javascript as the callback parameter. This is what the native toDataURL() method actually does – convert the Canvas to a base64 encoded image data string. Not being a Java developer, I had to look for external help, that’s where I came across Ryan Gillespie’s plugin which he developed some time back for the very purpose that I was looking for. But the code was kinda old and is not compatible with Phonegap 2.2.0 (this is the version that I am using for development) as there have been numerous changes in the Phonegap’s plugin architecture. I had to do some modifications to the code – mainly on the Java side. I used Ryan’s Java code and modified it a little bit. I wrote the javascript interface of the plugin entirely. Overall, thanks to Ryan for doing the tough part and its been possible to achieve the task. I had the modified plugin running successfully on older Android’s with Phonegap 2.2.0 and returning a valid base64 encoded image string of the HTML5 Canvas. Let’s quickly talk on the changes that I made. I will not discus on how to create custom Phonegap plugins in this post. For that you need to checkout the official documentation. It is better if you have some idea of creating custom plugins and what goes into creating a plugin, specifically the communication between JavaScript and Java.
  • 2. As I said earlier I modified Ryan’s Java class – CanvasPlugin.java. Download the file and check out the source. You will notice that the main changes are the new format for the overridden execute() method and it returns a boolean type now, also your plugin class should now extend the CordovaPlugin superclass, the third major change being the way callbackContext object now calls the success and error methods and in a way calls the javascript interface after the execute() method has finished it’s execution. There’s once more important change that I made is inside the custom getImageData() method – Base64.encodeBase64() has now been deprecated for the android.util.Base64 class, instead use Base64.encodeToString() method. So, mostly these changes made the Java class compatible with Phonegap 2.2.0. Now let’s check out the new JavaScript interface for the plugin. I did not use Ryan’s javascript file. I wrote a simple one myself. So get a copy of it first – CanvasPlugin.js. The logic is simple if you know how to write a javascript part of a Phonegap plugin. I am creating a canvasplugin method and exposing it to the global window object so that it is accessible across your code. The canvasplugin method takes two parameters – the HTML5 Canvas reference and the callback function reference which will be called once we have a result from Java side. Next important thing is calling the CanvasPlugin.java execute() method and passing it the right arguments. For that I would again suggest to go through the official documentation. You can modify the javascript code to make it better probably. With both the files ready, let’s see how to use it and get it working. Firstly you have to add these two files to your Phonegap Android project. Add the CanvasPlugin.js file inside assets/www/ folder and provide a reference to it in your index.html file, like this <script type="text/javascript" charset="utf-8" src="CanvasPlugin.js"></script> Then create a directory inside your project’s src folder that matches the package name of CanvasPlugin.java class. For our case make a directory – /org/apache/cordova/plugin inside src and then paste CanvasPlugin.java inside it. If you change the package name, make sure to change the directory structure as well. The package name can be found at the top of CanvasPlugin.java file. Next thing to do is to register the plugin in the config file – open res/xml/config.xml and then add the plugin details given below to the <plugins></plugins> section of the XML file. The name attribute is the Java class name and the value is the path of the class. This should match the package name. <plugin name="CanvasPlugin" value="org.apache.cordova.plugin.CanvasPlugin"/> And then call the plugin inside your javascript (your script.js file or so) code like this. (You can call this inside a button click handler or so), var canvas = document.getElementById("myCanvas");
  • 3. window.canvasplugin(canvas,function(val){ document.getElementById("myImg").src = val.data; }); where myCanvas is the ID of the HTML Canvas. The callback function receives the Base64 encode image string inside the data property of the returned value. Make sure to access it through val.data. Now you can use this as a source for an HTML image tag and you can get a preview image of your canvas. Here I am getting a Base64 encoded .png image string. If you need to change the mimeType, you can do that inside the CanvasPlugin.js file. Also you can pass that as a parameter to the javascript interface rather than hard code inside the CanvasPlugin.js file (which I did mistakenly). So pass it from your script.js to window.canvasplugin() call along with the canvas reference and the callback reference, as the third parameter. Lot of writing and English!! DOH!! But the cool plugin architecture has been able to overcome the shortcomings isn’t it.