HTML5练习之简陋版我画你猜(一)

来源:互联网 发布:网络有什么危害 编辑:程序博客网 时间:2024/05/16 17:24

一个好的创意将会成就一个人,就像我画你猜的开发者一样。最近学习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()"防止屏幕的拖动效果,具体实现还未尝试。


希望我会将其完善的更好。

0 0
原创粉丝点击