应用createjs库制作一个画画房间,可选颜色,有橡皮擦,画笔大小
时间: 2023-06-18 22:02:16 浏览: 180
creatine:肌酸是一个 JS 库,可为游戏开发的 CreateJS 套件提供支持
好的,下面是基于createjs库制作的画画房间代码,包括可选颜色、橡皮擦和画笔大小功能:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>画画房间</title>
<style>
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="600"></canvas>
<div>
<label>画笔颜色:</label>
<select id="color">
<option value="#000000">黑色</option>
<option value="#ff0000">红色</option>
<option value="#00ff00">绿色</option>
<option value="#0000ff">蓝色</option>
<option value="#ffff00">黄色</option>
</select>
<label>画笔大小:</label>
<select id="size">
<option value="5">小</option>
<option value="10" selected>中</option>
<option value="15">大</option>
</select>
<button id="eraser">橡皮擦</button>
<button id="clear">清空</button>
</div>
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<script>
var stage, canvas, shape, color, size, eraser, clear;
function init() {
canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
shape = new createjs.Shape();
stage.addChild(shape);
color = document.getElementById("color");
size = document.getElementById("size");
eraser = document.getElementById("eraser");
clear = document.getElementById("clear");
stage.addEventListener("stagemousedown", handleMouseDown);
stage.addEventListener("stagemousemove", handleMouseMove);
stage.addEventListener("stagemouseup", handleMouseUp);
eraser.addEventListener("click", function() {
color.value = "#ffffff";
});
clear.addEventListener("click", function() {
shape.graphics.clear();
stage.update();
});
createjs.Ticker.addEventListener("tick", stage);
}
function handleMouseDown(event) {
shape.graphics.setStrokeStyle(size.value, "round", "round")
.beginStroke(color.value)
.moveTo(stage.mouseX, stage.mouseY);
stage.addEventListener("stagemousemove", handleMouseMove);
}
function handleMouseMove(event) {
shape.graphics.lineTo(stage.mouseX, stage.mouseY);
stage.update();
}
function handleMouseUp(event) {
stage.removeEventListener("stagemousemove", handleMouseMove);
}
window.onload = function() {
init();
};
</script>
</body>
</html>
```
代码中,我们创建了一个画布和一个`Shape`对象用于存储画画的图形。通过`select`元素和`button`元素实现了可选颜色、橡皮擦和清空功能。在`init()`函数中,我们初始化了画布和`Shape`对象,并添加了鼠标事件监听器。在鼠标按下时,我们开始绘制图形,并在移动鼠标时不断更新绘制的图形。在鼠标松开时,停止绘制图形。最后,通过`Ticker`对象来更新画布显示。
阅读全文