画板小demo

demo地址:http://www.adanghome.com/js_demo/4/

用html5做的一个小demo,可以在图中画画,调整线条精细和颜色。目前在firefox下还不支持type=range,所以建议在chrome和opera下看。另外,opera对画布清空的支持还不好,而且box-reflect只有chrome支持,所以只在chromeg下的效果最好。

==========================================================

<!DOCTYPE html>
<html>
<head>
<title>阿当制作</title>
<meta charset="utf-8" />
<style>
#canvas{border:3px solid rgba(100,200,100,.5);-moz-border-radius:15px;border-radius:15px;margin:10px 0 0 100px;-webkit-box-shadow:10px 10px 10px #ccc;box-shadow:10px 10px 10px #ccc;-webkit-box-reflect:right 50px;}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<div>
<p><label for="canvas_lineWidth">线条粗细:</label><input type="range" min="1" max="10" value="1" id="canvas_lineWidth" /> <output for="canvas_lineWidth" id="canvas_lineWidthValue">1</output></p>
<p><label for="canvas_lineColor">线条颜色:</label><input type="color" id="canvas_lineColor" /></p>
<p><input type="button" value="清空画布" id="canvas_reset" /></p>
</div>
<script>
var eventUtil = {
getXY : function(e){
var x = e.pageX || e.clientX + document.documentElement.scrollLeft,
y = e.pagey || e.clientY + document.documentElement.scrollTop;
return [x,y];
},
getTarget : function(e){
return e.target || e.srcElement;
}
}

var domUtil = {
getXY : function(nod){
var x = nod.offsetLeft, y = nod.offsetTop;
while(nod.offsetParent){
nod = nod.offsetParent;
x += nod.offsetLeft;
y += nod.offsetTop;
}
return [x,y];
}
}

var canvas = document.querySelector("#canvas"),
context = canvas.getContext("2d"),
canvasKeyDown = false,
lineWidthInput = document.querySelector("#canvas_lineWidth"),
lineWidthValueNode = document.querySelector("#canvas_lineWidthValue"),
resetBtn = document.querySelector("#canvas_reset"),
strokeColor = document.querySelector("#canvas_lineColor");
context.lineWidth = 1;

lineWidthInput.onchange = function(e){
lineWidthValueNode.innerHTML = this.value;
context.lineWidth = this.value;
}

strokeColor.onchange = function(){
context.strokeStyle = this.value;
}

resetBtn.onclick = function(){
canvas.width = canvas.width;
}

function isKeyDown(){
return canvasKeyDown;
}

document.onmousedown = function(e){
e = e || event;
var xy = eventUtil.getXY(e),
target = eventUtil.getTarget(e);
if(target.id == "canvas"){
var nodXY = domUtil.getXY(target),
oX = xy[0] - nodXY[0],
oY = xy[1] - nodXY[1]; 
context.beginPath();
context.moveTo(oX,oY);
canvasKeyDown = true;
}
}

document.onmouseup = function(e){
canvasKeyDown = false;
context.closePath();
}

document.onmousemove = function(e){
if(!isKeyDown()) return;
e = e || event;
var xy = eventUtil.getXY(e),
target = eventUtil.getTarget(e);
if(target.id == "canvas"){
var nodXY = domUtil.getXY(target),
oX = xy[0] - nodXY[0],
oY = xy[1] - nodXY[1];
context.lineTo(oX,oY);
context.stroke();
}
}

</script>
</body>
</html>
原文地址:https://www.cnblogs.com/cly84920/p/4426657.html