createjs制作自定义画板
时间: 2023-12-05 11:51:10 浏览: 139
要使用CreateJS创建自定义画板,你需要先了解CreateJS的几个核心模块:EaselJS、TweenJS、SoundJS和PreloadJS。其中,EaselJS是用于创建图形和动画的模块,它提供了很多基本形状和对象,可以快速创建自定义画板。
下面是一个简单的CreateJS画板的代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>CreateJS画板示例</title>
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<script>
var canvas, stage, drawingCanvas, oldPt, oldMidPt, color, stroke, thickness;
var mouseMoveListener, mouseUpListener;
function init() {
// 创建画布
canvas = document.getElementById("canvas");
canvas.addEventListener("mousedown", handleMouseDown);
canvas.addEventListener("touchstart", handleMouseDown);
// 创建舞台
stage = new createjs.Stage(canvas);
stage.autoClear = false;
stage.enableDOMEvents(true);
// 创建画笔
drawingCanvas = new createjs.Shape();
stage.addChild(drawingCanvas);
stage.update();
// 设置画笔颜色、粗细、透明度
color = "#000000";
thickness = 1;
stroke = createjs.Graphics.getRGB(0, 0, 0, 0.5);
// 监听舞台事件
stage.addEventListener("stagemousemove", handleMouseMove);
}
function handleMouseDown(event) {
if (event.type == "mousedown") {
oldPt = new createjs.Point(stage.mouseX, stage.mouseY);
mouseMoveListener = stage.addEventListener("stagemousemove", handleMouseMove);
mouseUpListener = stage.addEventListener("stagemouseup", handleMouseUp);
} else if (event.type == "touchstart") {
oldPt = new createjs.Point(stage.mouseX, stage.mouseY);
mouseMoveListener = stage.addEventListener("stagemousemove", handleMouseMove);
mouseUpListener = stage.addEventListener("stagemouseup", handleMouseUp);
}
}
function handleMouseMove(event) {
var midPt = new createjs.Point(oldPt.x + stage.mouseX >> 1, oldPt.y + stage.mouseY >> 1);
drawingCanvas.graphics.clear().setStrokeStyle(thickness, "round", "round").beginStroke(stroke).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", mouseMoveListener);
stage.removeEventListener("stagemouseup", mouseUpListener);
}
</script>
</head>
<body onload="init();">
<canvas id="canvas" width="800" height="600"></canvas>
</body>
</html>
```
该示例中,我们创建了一个画布,然后在画布上监听鼠标事件,通过EaselJS的Shape对象绘制图形。在鼠标按下时,我们记录当前鼠标的位置,并在舞台上添加鼠标移动和鼠标抬起事件的监听器。在鼠标移动时,我们使用贝塞尔曲线绘制画笔的路径,并更新旧点和旧中点。在鼠标抬起时,我们移除鼠标移动和鼠标抬起事件的监听器,画笔的路径就完成了。
你可以通过修改color、thickness、stroke等参数来调整画笔的颜色、粗细和透明度,从而实现自定义画板。
阅读全文