Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

javascript - Security Error with canvas.toDataURL() and drawImage()

<!doctype html>
<canvas id="canvas" height="200" width="200"></canvas>
<div id="new"></div>
<script>
var div = document.getElementById("new");
var canvas = document.getElementById("canvas");  
var ctx = canvas.getContext("2d");  
var img = new Image();

img.src = 'http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png';
//img.src = 'local.png';

img.onload = function(){
    //draws the image on the canvas (works)
    ctx.drawImage(img,0,0,200,200);

    //creates an image from the canvas (works only for local.png)
    var sourceStr = canvas.toDataURL();

    //creates the img-tag and adds it to the div-container
    var newImage = document.createElement("img");
    newImage.src = sourceStr;
    div.appendChild(newImage);
}
</script>

This script creates a canvas with the html5-logo. From this canvas I want to create an image, using the "toDataURL()"-method. Here I get a security error.

Firefox says - Error: uncaught exception: [Exception... "Security error" code: "1000" nsresult: "0x805303e8 (NS_ERROR_DOM_SECURITY_ERR)"

Chrome says - Uncaught Error: SECURITY_ERR: DOM Exception 18

If I use the script with an image on the server it works fine. So it think this time it is really a feature and not a bug. Does anyone has an idea how I can create an image using canvas with out of an image form an other server? BTW: the error occurs if you run the site as a local file without a webserver.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are right, this is a security feature, not a bug.

If reading the Image (for instance with toDataURL or getImageData) would work, you could also read https://mail.google.com/mail/ from the context of your visitor get his emails or whatever.

Therefore, canvas elements have a origin-clean flag, which is set when external images are written to the canvas. In that case, you can no longer read from it.

You can read more about this topic here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...