Paper.js是一个开源的矢量图形的脚本,运行于HTM5的Canvas上,所以仅仅支持现代的浏览器。它提供了一个干净的画布/文档对象和许多功能强大的函数给用户去创建矢量图形和贝塞尔曲线。
demodemo源码
一、创建Angular项目
ng new paper-demo二、添加canvas标签 app.component.html
<div> <canvas #canvas></canvas> </div>app.component.scss
html, body, div { padding: 0; margin: 0; } div { canvas { width: 800px; height: 640px; border: 1px solid blue; } }三、引入相关文件,进行描绘 app.component.ts
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; import * as paper from 'paper'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements AfterViewInit { tool = new paper.Tool(); @ViewChild('canvas', { read: ElementRef, static: true }) canvas: ElementRef; ngAfterViewInit() { paper.setup(this.canvas.nativeElement); this.drawImg(); const layer = new paper.Layer(); let start; let length; this.tool.minDistance = 10; this.tool.onMouseDown = (e) => { start = e.point; length = layer.children.length; layer.activate(); }; this.tool.onMouseDrag = (e) => { const tl = new paper.Point(start); const size = new paper.Size((e.point.x - start.x), (e.point.y - start.y)); const rect = new paper.Rectangle(tl, size); const path = new paper.Path.Rectangle(rect); path.strokeColor = new paper.Color('red'); path.strokeWidth = 3; path.dashArray = [5, 1]; if (layer.children.length >= (length + 2) && layer.children.length >= 2) { layer.removeChildren(layer.children.length - 2, layer.children.length - 1); } }; } // 绘制背景图 drawImg() { // canvas的宽800 高640 const center = new paper.Point(400, 320); const raster = new paper.Raster('../assets/6.jpg'); raster.position = center; const img = raster.image; const size = raster.view.size; // 以最长边的缩放比例为原始比例,保证背景图片能够完全显示 const initScale = (size.width / img.width) - (size.height / img.height) > 0 ? (size.height / img.height) : (size.width / img.width); raster.scale(initScale); } }效果如下: