Frage

My canvas has image which programly generated from local file or from images from internet. When I try to save it using toDataURl function I get secure error. How can I save result (without server, using only js ) and is it possible?

I know about security rule but maybe there is some solution to bypass this rule

All my code is in github if need

War es hilfreich?

Lösung

Shame! Don't bypass rules built to provide security for our users.

The key to satisfying CORS security and still getting what you need is to let the user select the image file you need to load into canvas.

If the user selects the file, CORS security is satisfied and you can use the canvas as you need (including using canvas.toDataURL to save the canvas).

Here are the steps to let a user select a file from their local drive:

  1. Add an html input element with type="file"
  2. The user clicks browse on this element and selects their file
  3. When the user clicks OK, use window.URL.createObjectURL to create a URL from their selected file.
  4. Create a new Image and set its source to the URL you created in #3.
  5. Use context.drawImage to draw your new image on the canvas.
  6. The resulting canvas is CORS compliant so canvas.toDataURL will work.

Here's example code:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    #canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    $("#fileInput").change(function(e){
        var URL = window.webkitURL || window.URL;
        var url = URL.createObjectURL(e.target.files[0]);
        var img = new Image();
        img.onload = function() {
                canvas.width=img.width;
                canvas.height = img.height;
                ctx.drawImage(img,0,0);
                ctx.fillStyle="black";
                ctx.fillRect(0,canvas.height-30,canvas.width,30);
                ctx.fillStyle="white";
                ctx.font="18px verdana";
                ctx.fillText("I'm OK with CORS!",5,canvas.height-8);
        }
        img.src = url;
    });

    $("#save").click(function(){
        var html="<p>Right-click on image below and Save-Picture-As</p>";
        html+="<img src='"+canvas.toDataURL()+"' alt='from canvas'/>";
        var tab=window.open();
        tab.document.write(html);        
    });

}); // end $(function(){});
</script>
</head>
<body>
    <input type="file" id="fileInput">    
    <button id="save">Save</button><br>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top