在Angular6.x中使用 paper.js绘制矩形

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

效果如下:
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值