Skip to content

Instantly share code, notes, and snippets.

@fillano
Created October 21, 2010 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fillano/638699 to your computer and use it in GitHub Desktop.
Save fillano/638699 to your computer and use it in GitHub Desktop.
做出可以用滑鼠隨意塗鴉的效果
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<style>
div {
background: #AACCEE;
border: solid 1px #336699;
margin: 10px;
padding: 5px;
border-radius: 5px;
display: inline-block;
text-align: center
}
canvas {
cursor: pointer;
}
</style>
<script src="js/jquery-1.4.2.min.js"></script>
<script>
$(document).ready(function() {
var ctx = $('#canvas')[0].getContext('2d');
var drawing = false;
var oldPos = [0,0];
function drawLine(oldPos, newPos) {
ctx.save();
ctx.beginPath();
ctx.moveTo(oldPos[0], oldPos[1]);
ctx.lineTo(newPos[0], newPos[1]);
ctx.closePath;
ctx.stroke();
ctx.restore();
}
$('#canvas')[0].addEventListener('mousedown', function(e) {
drawing = true;
oldPos = [e.clientX-e.currentTarget.offsetLeft, e.clientY-e.currentTarget.offsetTop];
},false);
$('#canvas')[0].addEventListener('mouseup', function(e) {
drawing = false;
},false);
$('#canvas')[0].addEventListener('mousemove', function(e) {
e.preventDefault();
e.stopPropagation();
if(drawing) {
var newPos = [e.clientX-e.currentTarget.offsetLeft, e.clientY-e.currentTarget.offsetTop];
drawLine(oldPos, newPos);
oldPos = newPos;
}
return false;
},false);
$('#container')[0].addEventListener('mousemove', function() {
drawing = false;
});
});
</script>
</head>
<body>
<div id="container"><canvas id="canvas" width="640" height="480"></canvas></div><br>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment