问题
I'm attempting to use HTML5 to bring in an image file, draw it to the canvas, do some manipulation of it, then return the dataURL so that I can reference this newly generated image.
Here's a quick example of what the image loading code looks like:
<canvas id="myCanvas" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
c = document.getElementById("myCanvas");
cxt = c.getContext("2d");
var img=new Image();
img.src = "http://www.google.com/images/srpr/logo3w.png";
//img.src = 'image/placemark.png';
img.onload = function() {
cxt.drawImage(img, 0, 0);
}
console.log(c.toDataURL());
</script>
So, with the code like that the log of c.toDataURL() is a blank canvas, presumably because the log() call is executed before the draw() function finishes. If instead, I move that log call inside draw() I get a JavaScript error: SecurityError: The operation is insecure
If instead, I use the local image and put the log in to the draw function, I get the expected output there - but still blank canvas outside the function
I guess my actual question is: how can load in an external image to a canvas, and then modify it's contents in some fashion?
回答1:
Cross origin needs to be set on the server hosting the image making it a CORS enabled image if you want to do any sort of image modification.
If this is not set on the server side the only other option is to download the image via a server side proxy on the same domain as your script. As long as the image is coming from the same domain you'll be able to modify it.
回答2:
My code does not have the security error:
<pre>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<script src="Scripts/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
function WindowsLoad()
{
var c = document.getElementById("myCanvas");
var cxt = c.getContext("2d");
var img = new Image();
img.src = "http://www.google.com/images/srpr/logo3w.png";
//img.src = 'image/placemark.png';
img.onload = function () {
cxt.drawImage(img, 0, 0);
}
console.log(c.toDataURL());
}
</script>
<body onload="WindowsLoad();">
<form id="form1" runat="server">
<div>
<canvas id="myCanvas">
</canvas>
</div>
</form>
</body>
</html>
</pre>
来源:https://stackoverflow.com/questions/13883064/securityerror-load-an-image-in-canvas-modify-it-and-create-dataurl