SecurityError:操作不安全。使用Htmlcanvas

时间:2014-04-06 23:00:24

标签: javascript html5 canvas

尝试将图像转换为drag并将我的画布元素放置到PNG或Jpeg照片中(类似于polyvore的情绪板概念),这样我就可以一次性查看我在画布上放置的图像PNG或Jpeg照片。所以我可以保存它或对照片做任何事情。

但我遇到了一个SecurityError:操作不安全。当我按下保存并尝试转换数据以使用.alert()方法实际显示保存的图像给自己。我有什么想法可以通过这个错误来实现目标?谢谢!

以下是我的项目链接,可以直播: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);

1 个答案:

答案 0 :(得分:11)

要使用CORS请求图像,您可以在图像标记中指定用法:

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

或使用JavaScript:

var img = new Image;

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

但请求并不保证 - 服务器是否支持CORS。如果不是,则需要将映像移动到与页面相同的服务器(源)或支持CORS的其他服务器。

相关问题