Paper.js-导出栅格

时间:2018-08-18 10:33:04

标签: javascript svg paperjs

在paper.js库中运行以下代码

var raster = new paper.Raster({
    source: 'http://assets.paperjs.org/images/marilyn.jpg',
    position: paper.view.center
});

raster.exportSVG()

导致:

<image x="101" y="224" width="0" height="0" xlink:href="data:," fill="none" fill-rule="nonzero" stroke="none" stroke-width="1" stroke-linecap="butt" stroke-linejoin="miter" stroke-miterlimit="10" stroke-dasharray="" stroke-dashoffset="0" font-family="none" font-weight="none" font-size="none" text-anchor="none" style="mix-blend-mode: normal"></image>

如您所见:

xlink:href="data:,"

而不是包含所包含的图像。

用法是否正确?我应该如何导出栅格?

1 个答案:

答案 0 :(得分:2)

您在这里面临2个问题:

1-您正在尝试从尚未加载的图像中导出数据。
浏览器HTML请求是异步的,您必须等待图像加载后才能尝试使用它。
通过提供回调来完成。

2-然后您将遇到另一个与CORS相关的问题。
图像存储在与您的服务器不同的服务器上,默认情况下security reasons禁止使用图像数据。
因此,您有2种解决方案:

a-将图像与脚本存储在同一服务器上:

// create Raster with local path to your image
var raster = new Raster('./marilyn.jpg', paper.view.center);

// use PaperJS built-in callback to wait for loading
raster.onLoad = function ()
{
    // once image is loaded
    // you can do what you want with the raster
    console.log('image loaded, SVG = ', raster.exportSVG());
};

b-确保远程服务器允许CORS并在加载图像时添加CORS attribute

// create image
var image = new Image;

// add CORS attribute
image.crossOrigin = 'Anonymous';

// set remote source
image.src = 'http://assets.paperjs.org/images/marilyn.jpg';

// wait for image to be loaded
image.addEventListener('load', function ()
{
    // once image is loaded
    // create Raster with image element
    var raster = new Raster(image, paper.view.center);

    // now you can do what you want with the raster
    console.log('image loaded, SVG = ', raster.exportSVG());
});

编辑

实际上,仅使用Raster crossOrigin属性可以为CORS提供另一种更简单的解决方案。

var raster = new Raster({
    crossOrigin: 'anonymous',
    source: 'http://assets.paperjs.org/images/marilyn.jpg'
});
相关问题