简体   繁体   English

如何在客户端使用javascript从HTML标签创建图像?

[英]How to create image from HTML tags using javascript at client end?

I have an application, to download image as a confirmation receipt. 我有一个应用程序,可以下载图像作为确认收据。 User fill the application form and when he clicks ok a image will be downloaded for him. 用户填写申请表,然后单击确定,将为他下载图像。 I am going to implement this as an offline app(Phonegap framework). 我将其实现为离线应用程序(Phonegap框架)。

Could it possible to create a dynamic image files using Javascript? 可以使用Javascript创建动态图像文件吗?

Here are my codes, 这是我的代码,

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="http://www.w3.org/2000/svg">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
'<h3>Header</h3><em>I</em> like ' +
'<span style="color:white; text-shadow:0 0 2px blue;">' +
'cheese</span>' +
'</div>' +
'</foreignObject>' +
'</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {
  type: 'image/svg+xml;charset=utf-8'
});

The blob generated here is not compatible with file reader, i wont get image base64 if i use following codes? 此处生成的Blob与文件阅读器不兼容,如果使用以下代码,我将不会获得图像base64?

var reader = new FileReader();
reader.onload = function() {
var dataURL = reader.result;
 console.log(dataURL)
};
reader.readAsDataURL(svg);

Found one solution, which is not exact what i wanted but can solve my problem. 找到了一个解决方案,它不完全是我想要的,但可以解决我的问题。

var canvas = document.getElementById('textCanvas');
var context = canvas.getContext('2d');

context.font = '25pt Calibri';
context.fillStyle = '#891313';
context.fillText('My Header', 46, 30);
context.fillText('Description text, contains long ....', 20, 50);

console.log(context.canvas.toDataURL()) //this is the base64 formate of image

Basically here i create one canvas image and convert it to image, which later can easily downloaded. 基本上,我在这里创建一个画布图像并将其转换为图像,以后可以轻松下载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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