问题
I have used html2canvas.js
in my project for convert my element(body) into canvas and then convert canvas to image.
My element contains images that load from cross domain.
Canvas create from element is working perfectly, but when try to canvas.toDataURL("image/png");
it gives error SecurityError: The operation is insecure
Please help me to solve this issue.
canvas.toDataURL("image/png");
is working fine when image not load from cross domain.
Thanks in advance.
回答1:
Not really an html2canvas issue--just a security issue.
If your really lucky...
You can use imageObject.crossOrigin='anonymous'
when downloading your cross domain image. This requires both the server and browser to allow anonymous x-domain transfers. Sadly, almost all servers and most browsers don't yet allow.
Alternatively
Don't go cross-domain...serve that image on your own website.
Alternatively
Wrap the image request in a json request. Here's a script that does that: http://www.maxnov.com/getimagedata/
回答2:
Even I faced the same issue for my project. But, instead of using a html2canvasproxy.php (as many sites had advised me to), the html2canvas plugin has an inbuilt property which is false by default and which switches between cross domain images.
useCORS and allowTaint can be used in case of cross domain images and for countering canvas taint issues.
For Cross Domain Images issue, use useCors and set it to true. If you had modified cross domain images (like converting it into DataURI), the canvas might become tainted which html2canvas would not allow. Here, setting the allowTaint to true would solve the issue and make html2canvas to accept your canvas.
A sample implementation,
html2canvas(document.getElementById('mainImage'), {
allowTaint:true,
useCORS:true,
/*proxy:"lib/html2canvas_proxy/html2canvasproxy.php",*/
onrendered: function(canvas) {
var result = canvas.toDataURL();
}
});
Hope this helps. Or, if you/anyone has any other ideas, I would be glad to know. Thanks.
回答3:
I had a really difficult time figuring this out and no other answers worked for me nor provided the steps to take to stop this error from being thrown.
STEP BY STEP PROCESS:
Hide different elements in the container that you are taking a canvas screenshot of
and test whether the error is still thrown.
Eventually, I was able to determine that the select inputs were the culprits
.
- Check if there are any select inputs
- Hide the select inputs before taking the screenshot and add them back after (using jQuery
$('.selector').hide();
and$('.selector').show();
)
来源:https://stackoverflow.com/questions/16371316/html2canvas-securityerror-the-operation-is-insecure