2022-05-19 09:03:39
4.在 foreignObject 元素里面放入符合规范的 html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="canvas" width="200" height="200">
</canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" >' +
'<em>I</em> like ' +
'<span >' +
'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'});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
}
img.src = url;
</script>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container {
color: red;
}
</style>
</head>
<body>
<div class="container" >
Hello World!
</div>
<canvas id="canvas" width=200" height="200">
</canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" >' +
document.querySelector('.container').innerHTML +
'</div>' +
'</foreignObject>' +
'</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml'});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
}
img.src = url;
</script>
</body>
</html>
function convertHtml2Canvas() {
html2canvas(document.body, {
allowTaint: false,
taintTest: true
}).then(function(canvas) {
document.body.appendChild(canvas);
}).catch(function(e) {
console.error('error', e);
});
}
// Converts canvas to an image
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png", 0.1);
return image;
}
// Converts image to canvas; returns new canvas element
function convertImageToCanvas(image, startX, startY, width, height) {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(image, startX, startY, width, height, 0, 0, width, height);
return canvas;
}
function convertHtml2Canvas() {
html2canvas(document.body, {
allowTaint: false,
taintTest: true
}).then(function(canvas) {
var img = convertCanvasToImage(canvas);
document.body.appendChild(img);
img.onload = function() {
img.onload = null;
canvas = convertImageToCanvas(img, 0, 0, 384, 696);
img.src = convertCanvasToImage(canvas).src;
$(img).css({
display: 'block',
position: 'absolute',
top: 0,
left: 400 + 'px'
});
}
}).catch(function(e) {
console.error('error', e);
});
}