华域联盟 HTML5 浅谈基于Canvas的手绘风格图形库Rough.js

浅谈基于Canvas的手绘风格图形库Rough.js

前言

推荐一个基于Canvas的手绘风格图形JS库。

Rough.js

Rough.js是一个轻量的(大约8k),基于Canvas的可以绘制出粗略的手绘风格库。

提供绘制线条、曲线、弧线、多边形、圆形和椭圆的基础能力,同时支持绘制SVG路径。

Github:https://github.com/pshihn/rough

安装

下载链接:https://github.com/pshihn/rough/tree/master/dist

NPM

npm install --save roughjs

使用方法

const rc = rough.canvas(document.getElementById('canvas'));
rc.rectangle(10, 10, 200, 200); // x, y, width, height

线条和椭圆

rc.circle(80, 120, 50); // centerX, centerY, diameter
rc.ellipse(300, 100, 150, 80); // centerX, centerY, width, height
rc.line(80, 120, 300, 100); // x1, y1, x2, y2

填充

rc.circle(50, 50, 80, { fill: 'red' }); // fill with red hachure
rc.rectangle(120, 15, 80, 80, { fill: 'red' });
rc.circle(50, 150, 80, {
  fill: "rgb(10,150,10)",
  fillWeight: 3 // thicker lines for hachure
});
rc.rectangle(220, 15, 80, 80, {
  fill: 'red',
  hachureAngle: 60, // angle of hachure,
  hachureGap: 8
});
rc.rectangle(120, 105, 80, 80, {
  fill: 'rgba(255,0,200,0.2)',
  fillStyle: 'solid' // solid fill
});

草绘风格

rc.rectangle(15, 15, 80, 80, { roughness: 0.5, fill: 'red' });
rc.rectangle(120, 15, 80, 80, { roughness: 2.8, fill: 'blue' });
rc.rectangle(220, 15, 80, 80, { bowing: 6, stroke: 'green', strokeWidth: 3 });

SVG 路径

rc.path('M80 80 A 45 45, 0, 0, 0, 125 125 L 125 80 Z', { fill: 'green' });
rc.path('M230 80 A 45 45, 0, 1, 0, 275 125 L 275 80 Z', { fill: 'purple' });
rc.path('M80 230 A 45 45, 0, 0, 1, 125 275 L 125 230 Z', { fill: 'red' });
rc.path('M230 230 A 45 45, 0, 1, 1, 275 275 L 275 230 Z', { fill: 'blue' });

简单的SVG路径

结合Web Workers

如果在网页中有import Workly 这个Web Workers库,RoughJS会自动将所有的操作转移至web workers,来释放UI主线程。这个在使用RoughJS来创建复杂绘图(如地图)时非常有用。详细阅读相关内容

<script src="https://cdn.jsdelivr.net/gh/pshihn/workly/dist/workly.min.js"></script>
<script src="../../dist/rough.min.js"></script>

例子

https://github.com/pshihn/rough/wiki/Examples

API及文档

https://github.com/pshihn/rough/wiki

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。

本文由 华域联盟 原创撰写:华域联盟 » 浅谈基于Canvas的手绘风格图形库Rough.js

转载请保留出处和原文链接:https://www.cnhackhy.com/141183.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部