Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SecurityError: The operation is insecure. using Htmlcanvas [duplicate]

Trying to convert images I drag and place on my canvas element into a PNG or Jpeg photo (sort of a moodboard concept like polyvore) so I can view the images I place on the canvas all at once in one PNG or Jpeg photo. So I can save it or do whatever with the photo.

But I run into a SecurityError: The operation is insecure. when I press save and try convert the data to actually show the saved image to myself using the .alert() method. Any ideas how I can get past this error to accomplish the goal? Thank You!

Here is a link to my project to view it live: http://amechi101.github.io/moodboard/

Html:

 <div id="container" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
 <div class="buttonMoodBoard">
    <button class="btn btn-primary btn-lg" id="save">Save Moodboard</button> 
 </div>

Javascript:

var stage = new Kinetic.Stage({
                container: 'container',
                width: 500,
                height:500
            });

            var layer = new Kinetic.Layer();

uni_width = 120;

function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("Text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    data = ev.dataTransfer.getData("Text");
    img_received = document.getElementById(data);
    ratio = img_received.height / img_received.width;

    var c=document.getElementById("container");
    drop_x=ev.pageX-c.offsetLeft;
    drop_y=ev.pageY-c.offsetTop;

    var imageObj = new Image();
    imageObj.src = img_received.src;
    imageObj.onload = function() {
        var new_image = new Kinetic.Image({
        x: drop_x - uni_width / 2,
        y: drop_y - uni_width * ratio / 2,
        image: imageObj,
        width: uni_width,
        height: uni_width * ratio,
        draggable: true
        });

    // add the shape to the layer
    layer.add(new_image);

    // add the layer to the stage
    stage.add(layer);
  };
}

//saving to data base via Json
document.getElementById('save').addEventListener('click', function (canvas) {
        var json = stage.toJSON();



    var canvas = document.getElementsByTagName("canvas");
    var img    = canvas[0].toDataURL("image/png");

    var alertJson = alert(img);
    console.log(json, alertJson);   
}, false);
like image 888
Amechi Avatar asked Oct 31 '25 16:10

Amechi


1 Answers

To request an image using CORS you can either specify usage in the image tag:

<img src="..." crossOrigin="anonymous">

or using JavaScript:

var img = new Image;

img.onload = loaded;            // load handler
img.crossOrigin = 'anonymous';
img.src = '...';

A request is no guarantee however - It will be up to the server to support CORS or not. If it doesn't you need to move the image to the same server (origin) as the page or to another server which do support CORS.