扫一扫分享
Paper.js是一个开源的矢量图形的脚本,运行于HTM5的Canvas上,所以仅仅支持现代的浏览器。它提供了一个干净的画布/文档对象和许多功能强大的函数给用户去创建矢量图形和贝塞尔曲线。所有这些功能都整齐地包在一个设计良好的,一致的和干净的接口里。
Paper.js是基于Scriptographer(一个有着活跃的社区和超过10年的发展的针对Adobe Illustrator的脚本环境)的。
虽然体量上看着不小,但功能是真全:路径绘制、贝塞尔曲线、矢量运算、鼠标事件、SVG 导入导出,基本上 Canvas 能干的活它都给包了。还有一个 paper-core 版本,去掉了 PaperScript 语法支持和 Acorn.js 解析器,体积能再省一点,适合只用 JavaScript 直接调用的场景。
1、npm 安装
1npm i paper导入依赖
// CommonJS
const paper = require('paper')
// ESM
import paper from 'paper'2、浏览器端引入
<!-- 传统 script 引入 -->
<script src="https://cdn.jsdelivr.net/npm/paper@0.12.18/dist/paper-full.min.js"></script>1、基础图形绘制
<canvas id="canvas" resize></canvas>
<!-- 引入 Paper.js -->
<script src="https://cdn.jsdelivr.net/npm/paper@0.12.18/dist/paper-full.min.js"></script>
<script>
paper.setup(document.getElementById('canvas'))
const center = paper.view.center
// 绘制圆形
new paper.Path.Circle({
center: [center.x - 180, center.y - 60],
radius: 60,
fillColor: '#ff4757',
strokeColor: '#2f3542',
strokeWidth: 3
})
// 贝塞尔曲线画图
const curve = new paper.Path({
strokeColor: '#2ed573',
strokeWidth: 4,
strokeCap: 'round'
});
[
[center.x + 80, center.y + 60],
[center.x + 140, center.y - 20],
[center.x + 220, center.y + 80],
[center.x + 300, center.y - 10],
].forEach(function(point) {
curve.add(new paper.Point(point[0], point[1]))
})
curve.smooth()
// 画个矩形
new paper.Path.Rectangle({
point: [center.x + 40, center.y - 120],
size: [120, 80],
fillColor: '#1e90ff',
strokeColor: '#2f3542',
strokeWidth: 2,
radius: 8
})
// 绘制直线
new paper.Path.Line({
from: [80, center.y + 80],
to: [350, center.y + 80],
strokeColor: '#ffa502',
strokeWidth: 4,
strokeCap: 'round'
})
// 绘制多边形(六边形)
const sides = 6
const polygon = new paper.Path.RegularPolygon({
center: [center.x - 180, center.y + 100],
sides: sides,
radius: 50,
fillColor: '#a55eea',
strokeColor: '#2f3542',
strokeWidth: 2
})
paper.view.draw()
</script>仅供个人学习参考/导航指引使用,具体请以第三方网站说明为准,本站不提供任何专业建议。如果地址失效或描述有误,请联系站长反馈~感谢您的理解与支持!
手机扫一扫预览