Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert canvas to image and open in new window using ruby on rails and javascript

I'm pretty stuck at this problem and hope you guys can help me.

What I'm trying to achieve is upon clicking a link, button or image, which ever seems simpler, I convert canvas into image using toDataURL. After that a new window containing this image is opened.

How do I pass the data url generated from toDataURL to a new window using ruby on rails?

Thanks in advance.

like image 241
Mich Avatar asked Mar 23 '11 10:03

Mich


3 Answers

First off, this has not much to do with Rails. You can use Ruby to tackle this problem, though.

First fetch the content of the canvas as you're already doing:

var dataURL = canvas.toDataURL("image/png");

At this point you could simply open a new window with Javascript and open the image straight in there (no server interaction needed):

var window = window.open();
window.document.write('<img src="'+dataURL+'"/>');

$('a.my-link').click(function(){
  open().document.write('<img src="'+dataURL+'"/>');
  return false;
});

Here's a small fiddle to illustrate this: http://jsfiddle.net/XtUFt/

Or you could send the pure base64 string to the server and have your app create an actual image and use a view to render it:

var base64 = dataURL.replace(/^data:image\/(png|jpg);base64,/, "") ;
var window = window.open('http://www.yourapp.com/controller/action?base64='+base64);

!This is a simplified example and assumes a very small image. If your image is anyhow bigger you'll have to use a 'post' request because your URL will not carry the data since the string is simply too long!

And on the server you then can use to create the image:

require 'base64'
File.open('your/image/path/and/name.gif', 'wb') do|f|
  f.write(Base64.decode64(params[:base64]))
end

Then it's just a question of opening the image and rendering a view accordingly.

like image 187
polarblau Avatar answered Oct 22 '22 17:10

polarblau


I am late for this but here is one quick dirty liner that solves this question:

 window.open(document.getElementById("mycanvas").toDataURL());

Hope this helps someone in the near future.

like image 25
revobtz Avatar answered Oct 22 '22 17:10

revobtz


My approach:

var dataURL = canvas.toDataURL("image/png");
var newTab = window.open(dataURL, 'Image');
newTab.focus();

It May be helps someone in future.

like image 1
Hokusai Avatar answered Oct 22 '22 16:10

Hokusai