javascript - Canvas 到 png 不工作 fabricjs

标签 javascript jquery canvas fabricjs

这是我使用 FabricJS 将 Canvas 导出到图像的代码:

$("#canvas2png").click(function(){
    canvas.isDrawingMode = false;

    if(!window.localStorage){alert("This function is not supported by your browser."); return;}
    // to PNG
    window.open(canvas.toDataURL('png'));
});

https://jsfiddle.net/ridwanamirsene/nL4jbLon/1/

为什么当我点击 canvas 2 png 按钮时..它不起作用..

它正在运行样本 http://jsfiddle.net/softvar/9hrcp/通过软件

我该如何解决这个问题?

最佳答案

你的图片有跨域问题:

VM71 fabric.min.js:3 Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.(…)

CORS enabled image

What is a "tainted" canvas?

Although you can use images without CORS approval in your canvas, doing so taints the canvas. Once a canvas has been tainted, you can no longer pull data back out of the canvas. For example, you can no longer use the canvas toBlob(), toDataURL(), or getImageData() methods; doing so will throw a security error.

我改变了你的初始化方法:

initialize: function(src) {
        this.image = new Image();
        this.image.crossOrigin = "Anonymous";
        this.image.src = src;
         this.image.onload = (function() {
            this.width = this.image.width;
            this.height = this.image.height;
            this.loaded = true;
            this.setCoords();
            this.fire('image:loaded');
            canvas.renderAll(paper); 
        }).bind(this);
    },

我使用了来自维基媒体的已启用 cors 图像:

var imgs = [

    'https://upload.wikimedia.org/wikipedia/commons/0/0e/American_Black_Bear_%283405475634%29.jpg', // cat
    'https://upload.wikimedia.org/wikipedia/commons/0/0e/American_Black_Bear_%283405475634%29.jpg' // mouse
];

现在your forked fiddle有效。

关于javascript - Canvas 到 png 不工作 fabricjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40993139/

相关文章:

javascript - 用图像/ Sprite 中的另一种颜色替换特定颜色

javascript - Parsley 在初始验证调用后阻止 keydown 验证

javascript - 模态弹出窗口打开时背景屏幕变暗

php - 使用 Jquery 将 URL 变量传递给 PHPExcel

javascript - $.getScript,可以给包含的脚本一个id吗?

jquery - 在 Canvas 顶部制作交互式文本区域

JavaScript 闭包。输入未定义值会停止脚本。有时

javascript - 如何使用javascript或angularjs从字符串中提取html标签的内容?

javascript - 动画在 jQuery 1.6 中被破坏了!

javascript - 如何使用 Easeljs 将 Click 事件添加到 spriteSheet?