简体   繁体   中英

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.

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.

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.

My approach:

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

It May be helps someone in future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM