最近写了一个增强html canvas功能的库miracle-canvas,使用miracle-canvas可以在html canvas上添加可移动、缩放和旋转的图元,目前图元支持自定义形状和图片。
功能如下图所示:
可以通过npm或者yarn安装:
npm install miracle-canvas
也可以通过cdn引入:
<script src="https://cdn.jsdelivr.net/gh/pengfeiw/miracle-canvas@1.0.6/src/bundle.js"></script>
1.引入miracle-canvas
import Miracle from "miracle-canvas";
const miracle = new Miracle(canvas);
2.添加图元
// create a rectangle
const rect = new PolyShape([
new Point(150, 30),
new Point(200, 30),
new Point(200, 120),
new Point(150, 120)
], false);
rect.filled = false; // set filled false
rect.closed = true;
// create a circle
const circle = new Circle(new Point(400, 400), 50);
circle.strokeStyle = "green";
// create a triangle
const triangle = new PolyShape([
new Point(100, 100),
new Point(150, 150),
new Point(100, 200)
]);
triangle.filled = true; // set filled true
triangle.closed = true;
triangle.fillStyle = "gray";
// create image with specific size
const img = new Image(new Point(200, 300), "/image.png", {
height: 150,
width: 180
});
// add the above entities
miracle.addEntity(circle, rect, triangle, img);
3.可以设置图元是否可见,控制点(平移、旋转、缩放)是否可见
// set the visible of entity
triangle.visible = false;
// set visible of operate control
miracle.xLocked = false;
miracle.yLocked = false;
miracle.diagLocked = false;
miracle.rotateLocked = false;
这个库的基本功能才写完,后面我也会一直更新功能的,会增加更多类型的图元,每次更新我会第一时间发布到npm,并同步到github上。这个库可能会有一些bug,如果有问题欢迎在下方留言,我会加快改进修正,在这里也提前说一声谢谢。
Miracle.limitInCanvas
属性可以限制图元在canvas内,修复了一些bug,也增加cdn引入库使用,具体内容查看github。github源码:https://github.com/pengfeiw/miracle-canvas
github demo:https://github.com/pengfeiw/miracle-canvas-demo
npm包:https://www.npmjs.com/package/miracle-canvas?activeTab=dependents