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

How to resize a raster(image) in paper.js?

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

JS

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

Paper.js光栅文档中默认没有这种方法。不过,这不会阻止您添加自己的。您可以执行以下操作:

/**
 * 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

您可以通过以下方式缩放图像以适应 canvas:

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);