Created
October 21, 2012 11:00
-
-
Save tkojitu/3926685 to your computer and use it in GitHub Desktop.
draw lines in a canvas. translate event coord to canvas coord.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> | |
<meta name="viewport" content="initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, width=device-width, target-densitydpi=device-dpi"> | |
<title>Draw Lines</title> | |
<style> | |
body { | |
margin: 0px; | |
padding: 0px; | |
} | |
canvas { | |
border: 1px solid #9C9898; | |
} | |
</style> | |
<script> | |
var mouse_down = false; | |
var pos_x = -1; | |
var pos_y = -1; | |
function getCanvas() { | |
return document.getElementById("canvas"); | |
} | |
window.onload = function() { | |
initCanvas(); | |
preventScroll(); | |
} | |
function initCanvas() { | |
var canvas = getCanvas(); | |
canvas.addEventListener("touchstart", onTouchStart, false); | |
canvas.addEventListener("touchmove", onTouchMove, false); | |
canvas.addEventListener("touchend", onTouchEnd, false); | |
} | |
function preventScroll() { | |
document.body.ontouchstart = function(e) { e.preventDefault(); }; | |
} | |
function drawLine(x1, y1, x2, y2) { | |
var canvas = getCanvas(); | |
var ctx = canvas.getContext('2d'); | |
var rect = canvas.getBoundingClientRect(); | |
ctx.beginPath(); | |
ctx.moveTo(x1 - rect.left, y1 - rect.top); | |
ctx.lineTo(x2 - rect.left, y2 - rect.top); | |
ctx.closePath(); | |
ctx.stroke(); | |
} | |
function onTouchStart(event) { | |
mouse_down = true; | |
pos_x = event.touches[0].pageX; | |
pos_y = event.touches[0].pageY; | |
} | |
function onTouchMove(event) { | |
var x; | |
var y; | |
if (!mouse_down) return; | |
x = event.touches[0].pageX; | |
y = event.touches[0].pageY; | |
drawLine(pos_x, pos_y, x, y); | |
pos_x = x; | |
pos_y = y; | |
} | |
function onTouchEnd(event) { | |
mouse_down = false; | |
} | |
</script> | |
</head> | |
<body> | |
<canvas width=790 height=100></canvas> | |
<canvas width=200 height=100></canvas> | |
<canvas id="canvas" width=580 height=480></canvas> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment