HTML5练习之简陋版我画你猜(一)
16lz
2021-01-22
一个好的创意将会成就一个人,就像我画你猜的开发者一样。最近学习HTML5中的canvas,故模仿其以达到练习目的。
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>Guess</title>
<style>
h1 {
text-align:center;
}
#user {
position:absolute;
top:12%;
left:3%;
height:479px;
width:300px;
list-style:none;
overflow:hidden;
border:2px #000 solid;
}
#paint {
margin:10px 425px;
padding:0px auto;
border:1px #000 solid;
}
#sendUp {
margin:auto 425px;
}
#chat {
position:absolute;
top:10%;
left:69%;
height:479px;
width:auto;
list-style:none;
overflow:hidden;
}
</style>
</head>
<body>
<h1>Guess</h1>
<ul id=user>在线玩家们</ul>
<canvas id=paint width=500 height=500>No supporting!</canvas>
<form id=sendUp>
<input id=guessResult type=text placeholder=你想说甚么? />
<input id=send type=button value=提交 onclick=sendResult() />
</form>
<ul id=chat><p>大家的看法:</p></ul>
<script>
var paint = document.getElementById('paint');
var ptx = paint.getContext('2d');
//构建绘图环境
ptx.strokeStyle = 'rgba(0,0,0,255)';
ptx.lineWidth = '3px';
//设置初始笔刷
var resultText = document.getElementById('guessResult');
var views = document.getElementById('chat');
function painting () {
paint.onmousedown = function (event) {
ptx.save();
var event = event || window.event;
ptx.moveTo(event.clientX - paint.offsetLeft,event.clientY - paint.offsetTop);
paint.onmousemove = function (event) {
var event = event || window.event;
ptx.lineTo(event.clientX - paint.offsetLeft,event.clientY - paint.offsetTop);
ptx.stroke();
}
paint.onmouseup = function () {
paint.onmousemove = null;
}
paint.onmouseout = function () {
paint.onmousemove = null;
}
ptx.restore();
}
}
function sendResult() {
var newView = document.createElement('li');
var agree = document.createElement('a');
newView.innerHTML = "<br>某人认为是:" + resultText.value + '<br>';
agree.innerHTML = "赞同";
agree.href = "javascript:;";
newView.appendChild(agree);
if (document.getElementsByTagName('li').length <= 0) {
views.appendChild(newView);
} else {
views.insertBefore(newView,document.getElementsByTagName('li')[0]);
}
resultText.value = "";
}
window.onload = function () {
painting();
}
</script>
<body>
</html>
仅仅完成了最基本的布局与简单功能,画线的实现是通过对画布上鼠标事件的监听,当鼠标键按下时,确定起始点,当鼠标拖动时,实时画线到每一点,当鼠标键被松开时清除事件。如果是在触摸屏幕的话应该可以通过——"onTouchStart","onTouchMove","onTouchEnd"等事件实现,不过切记要在画线之前调用"event.preventDefalut()"防止屏幕的拖动效果,具体实现还未尝试。
希望我会将其完善的更好。
更多相关文章
- 我可以使用onBlur事件对TextBox进行日期检查吗?
- jQuery:添加事件监听器是否覆盖相同事件的前一个监听器?
- Web小练习-JavaScript事件的简单练习,监听鼠标的移动
- 掌握JavaScript中的事件监听
- 使用js更改抛出事件的输入值
- 如何在详细信息标记的结束事件上添加CSS转换?
- 无法从按钮onclick事件ASP.NET 4调用Javascript函数
- js获取点击事件的位置,兼容主流浏览器
- 为什么jquery click事件在plunker中工作但在任何浏览器中都没有