DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> HTML基礎知識 >> HTML5教程 >> HTML5畫板實驗
HTML5畫板實驗
編輯:HTML5教程     
使用HMTL5 Canvas實現畫板功能,可以生成圖片。

在線塗鴉:http://hovertree.com/texiao/html5/13/

完整代碼:
<!DOCTYPE html>
<html>
<head>
<title>HTML5畫板實驗 - 何問起</title><base target="_blank" />
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">body{margin:0px;}
#panelHovertree {
background: red;
}
</style>
</head>

<body>

<canvas id="panelHovertree"></canvas>

<div>
<button onClick="clean();">清 空</button>
<button onClick="save();">生成圖片</button>
</div>

<img id='img' alt='何問起畫板,生成圖片後右鍵可以保存,請塗鴉……' />

<div class="hvtholder">
<h2>HTML5畫板</h2>
<br />
<a href="http://hovertree.com/">首頁</a> <a href="http://hovertree.com/texiao/">特效</a>
<a href="http://hovertree.com/menu/html5/">HTML5</a>
<a href="http://hovertree.com/h/bjae/edq0yn76.htm">原文</a>
<a href="http://hovertree.com/map/">導航</a>
</div>
<!--<p id="textId">sdfsdfs</p>-->
<!--<textarea id="log" cols="30" rows="5"></textarea>-->
<script type="text/javascript">
var canvas,board,img;
canvas = document.getElementById('panelHove'+'rtree');
img= document.getElementById('img');

canvas.height = 300;
canvas.width = 300;

board = canvas.getContext('2d');

var mousePress = false;
var last = null;

function beginDraw(){
mousePress = true;
}

function drawing(event){
event.preventDefault();
if(!mousePress)return;
var xy = pos(event);
if(last!=null){
board.beginPath();
board.moveTo(last.x,last.y);
board.lineTo(xy.x,xy.y);
board.stroke();
}
last = xy;

}

function endDraw(event){
mousePress = false;
event.preventDefault();
last = null;
}

function pos(event){
var x,y;
if(isTouch(event)){
x = event.touches[0].pageX;
y = event.touches[0].pageY;
}else{
x = event.offsetX+event.target.offsetLeft;
y = event.offsetY+event.target.offsetTop;
}
// log('x='+x+' y='+y);
return {x:x,y:y};
}

function log(msg){
var log = document.getElementById('log');
var val = log.value;
log.value = msg+'n'+val;
}

function isTouch(event){
var type = event.type;
if(type.indexOf('touch')>=0){
return true;
}else{
return false;
}
}

function save(){
//base64
var dataUrl = canvas.toDataURL();
//document.getElementById('textId').innerText(dataUrl);
// document.getElementById("textId").innerHTML = dataUrl;
// dataUrl = dataUrl.replace("image/png","image/octet-stream");
img.src = dataUrl;
}


function clean(){
board.clearRect(0,0,canvas.width,canvas.height);

}

board.lineWidth = 1;
board.strokeStyle="#0000ff";


canvas.onmousedown = beginDraw;
canvas.onmousemove = drawing;
canvas.onmouseup = endDraw;
canvas.addEventListener('touchstart',beginDraw,false);
canvas.addEventListener('touchmove',drawing,false);
canvas.addEventListener('touchend',endDraw,false);
</script>

<!--[ lim_{x to 0} ]-->
</body>

</html>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved