如何在paper.js中调整光栅(图像)的大小?

时间:2017-11-06 12:07:57

标签: javascript html canvas paperjs

我使用 Paper.js 文档中的代码加载了图片。但我想改变图像大小。我不想缩放图像,而是为图像设置尺寸。有没有办法在 Paper.js 中设置图片的widthheight

JS

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

2 个答案:

答案 0 :(得分:1)

默认情况下, Paper.js Raster文档中没有此类方法。这不会阻止您添加自己的。您可以执行以下操作:

/**
 * Re-scales the Raster object to the new dimensions.
 * Method added to the Raster's prototype to easily
 * call it from the raster object itself.
 */
Raster.prototype.rescale = function(width, height) {
    this.scale(width / this.width, height / this.height);
};

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

raster.rescale(200, 100);

这是一个codepen,其中有一个工作示例。

答案 1 :(得分:0)

您可以通过以下方式缩放图像以适合画布:

const image = new paper.Raster('http://assets.paperjs.org/images/marilyn.jpg');
const widthRatioOfCanvasToImage =
  paper.view.bounds.width / image.bounds.width;
const heightRatioOfCanvasToImage =
  paper.view.bounds.height / image.bounds.height;
const scale = Math.min(
  widthRatioOfCanvasToImage,
  heightRatioOfCanvasToImage
);
image.scale(scale, scale);