我使用html2canvas将div转换为canvas并使用toDataURL()将其转换为image。创建通过回形针上载并处于开发模式的图像后,在上传到AWS的生产模式下,它将保存在本地存储中。这里的问题是保存的图像,在开发过程中,图像显示为div,而在生产中,创建的图像不是开发中的图像。 这是js文件。
$(function() {
$("#campaign_submit").click(function(e) {
e.preventDefault();
$('body').waitMe({ effect : 'bounce', text : 'Loading'});
$('#price').val($('#amount').val());
html2canvas($("#containertoimage"), {
onrendered: function(canvas) {
theCanvas = canvas;
//document.body.appendChild(canvas);
var img = canvas.toDataURL("image/jpg");
if (img.length > 10)
{
$.ajax({
url: "/campaigns/image",
type: "POST",
dataType: "json",
data: {img_data: img},
success: function(resp){
$.ajax({
type: "POST",
url: '/campaigns/create_campaign',
dataType: "json",
data: $("#new_campaign").serialize(), // serializes the form's elements.
success: function(data)
{
window.location="/campaigns/"+data.url
}
});
}
,
error: function(resp){
}
});
}
//$('#svg_data_front').val(img);
}
});
});
});
这是创建图像的方法
def image
name = Time.now.to_i
session[:filename] = name
data = params[:img_data]
image_data = Base64.decode64(data['data:image/png;base64,'.length .. -1])
File.open("#{Rails.root}/public/#{name}.jpg", 'wb') do |f|
f.write image_data
link = "#{Rails.root}/public/#{name}.jpg"
respond_to do |format|
format.json { render :json => {success: true, file_link: link} }
end
end
end
这是将图像保存到模型
的方法def create_campaign
@campaign = current_user.campaigns.build(campaign_params)
if @campaign.save
@campaign.update_attributes(:image => File.open("#{Rails.root}/public/#{session[:filename]}.jpg"))
session[:filename] = nil
flash[:success] = "Campaign successfully created"
respond_to do |format|
format.json { render :json => {success: true, url: @campaign.url} }
end
else
@master_product = MasterProduct.all
@product_types = MasterProduct.distinct_product_type
render 'new'
end
end