用createjs实现绘图板
时间: 2023-06-13 19:06:32 浏览: 129
好的,以下是用createjs实现绘图板的基本步骤:
1. 创建画布
首先,我们需要在HTML中创建一个画布元素,如下所示:
```html
<canvas id="canvas" width="800" height="600"></canvas>
```
2. 初始化createjs
在JavaScript中,我们需要初始化createjs库,创建一个Stage对象和一个Shape对象。Stage对象是用来管理画布上所有对象的容器,Shape对象是用来绘制图形的。同时,我们还需要为画布添加鼠标事件监听器,以便能够响应用户的绘图操作。代码如下:
```javascript
var stage, shape, oldPt, oldMidPt, drawColor, drawSize;
function init() {
stage = new createjs.Stage("canvas");
shape = new createjs.Shape();
stage.addChild(shape);
drawColor = "#000000";
drawSize = 5;
stage.addEventListener("stagemousedown", handleMouseDown);
stage.addEventListener("stagemouseup", handleMouseUp);
stage.addEventListener("stagemousemove", handleMouseMove);
}
function handleMouseDown(event) {
oldPt = new createjs.Point(stage.mouseX, stage.mouseY);
oldMidPt = oldPt.clone();
stage.addEventListener("stagemousemove", handleMouseMove);
}
function handleMouseMove(event) {
var midPt = new createjs.Point(oldPt.x + stage.mouseX >> 1, oldPt.y + stage.mouseY >> 1);
shape.graphics.setStrokeStyle(drawSize, 'round', 'round')
.beginStroke(drawColor)
.moveTo(midPt.x, midPt.y)
.curveTo(oldPt.x, oldPt.y, oldMidPt.x, oldMidPt.y);
oldPt.x = stage.mouseX;
oldPt.y = stage.mouseY;
oldMidPt.x = midPt.x;
oldMidPt.y = midPt.y;
stage.update();
}
function handleMouseUp(event) {
stage.removeEventListener("stagemousemove", handleMouseMove);
}
init();
```
3. 绘制图形
我们使用Shape对象的graphics属性来绘制图形。在绘图时,我们需要指定线条的颜色、宽度、笔触等属性,然后使用moveTo()和curveTo()方法来绘制曲线。代码如下:
```javascript
shape.graphics.setStrokeStyle(drawSize, 'round', 'round')
.beginStroke(drawColor)
.moveTo(midPt.x, midPt.y)
.curveTo(oldPt.x, oldPt.y, oldMidPt.x, oldMidPt.y);
```
4. 清空画布
如果需要清空画布,我们可以使用Shape对象的graphics属性的clear()方法来清除所有绘制的图形。代码如下:
```javascript
function clear() {
shape.graphics.clear();
stage.update();
}
```
以上就是用createjs实现绘图板的基本步骤。你可以根据自己的需要添加其他功能,如选择颜色、选择画笔大小等。
阅读全文