我是JS和一般开发人员的新手,但我希望能得到一些帮助来解决我几天试图解决的问题。
基本上,我试图让HTML2Canvas与Angular一起玩。我的部分HTML文件中有一个div(ID是'invoice'),我的控制器中有以下内容:
sampleApp.controller('InvoiceController', function($scope) {
$(document).ready(function(){
var source = document.getElementById('invoice');
$( '.submit' ).click(function() {
html2canvas(source, {
logging: 'on',
allowTaint: 'true',
onrendered: function(canvas) {
var myImage = canvas.toDataURL("image/jpeg");
window.open(myImage);
}
});
});
});
我完全不知道为什么这不起作用。该脚本运行没有任何错误,但它只是踢出一个没有图像的空白页面。它看起来像是DOM的东西,因为这是我在控制台中得到的:
html2canvas: Preload starts: finding background-images html2canvas.js:21
html2canvas: Preload: Finding images html2canvas.js:21
html2canvas: Preload: Done. html2canvas.js:21
html2canvas: start: images: 0 / 0 (failed: 0) html2canvas.js:21
Finished loading images: # 0 (failed: 0) html2canvas.js:21
html2canvas: Renderer: Canvas renderer done - returning canvas obj
编辑:我想补充一点,我知道它的另一个原因是在Angular中如何加载DOM是因为使用document.body作为var工作。不过,我只想用单个div制作图像。
以下是我在我的项目中使用的确切指令,它也适用于svg,因此也渲染图表:
(function () {
'use strict';
angular
.module('myModule')
.directive('camera', camera);
camera.$inject = ['$rootScope'];
/* @ngInject */
function camera($rootScope) {
var directive = {
link: link,
restrict: 'A'
};
return directive;
function link(scope, element, attrs) {
$rootScope.$on('capture', function (event, deferred) {
event.stopPropagation();
renderSvg(element);
//method to render the SVG's using canvg
function renderSvg(element) {
// First render all SVGs to canvases
var elements = element.find('svg').map(function () {
var svg = $(this);
var canvas = $('<canvas></canvas>');
svg.replaceWith(canvas);
// Get the raw SVG string and curate it
var content = svg.wrap('<p></p>').parent().html();
content = content.replace(/xlink:title="hide\/show"/g, "");
content = encodeURIComponent(content);
svg.unwrap();
// Create an image from the svg
var image = new Image();
image.src = 'data:image/svg+xml,' + content;
image.onload = function () {
canvas[0].width = image.width;
canvas[0].height = image.height;
// Render the image to the canvas
var context = canvas[0].getContext('2d');
context.drawImage(image, 0, 0);
};
return {
svg: svg,
canvas: canvas
};
});
// At this point the container has no SVG, it only has HTML and Canvases.
html2canvas(element[0], {
useCORS: true,
allowTaint: true,
onrendered: function (canvas) {
// Put the SVGs back in place
elements.each(function () {
this.canvas.replaceWith(this.svg);
});
var dataURL = null;
try {
dataURL = canvas.toDataURL("image/png", 0.9);
deferred.resolve(dataURL);
}
catch (e) {
deferred.reject(e);
}
}
});
}
});
}
}
})();
引用上面的指令并在控制器中使用以下代码来调用指令中的功能:
var deferred = $q.defer();
$scope.$emit('capture', deferred);
deferred.promise.then(function (screenshot) {
//do something with screenshot (Base64Url for .png type)
});