Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
your very own self drawing draw!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Canvas</title>
<style type="text/css">
canvas { border: 1px solid black; }
</style>
</head>
<body>
<canvas id="canvas" onclick="draw(event)" style="margin:0;padding:0;" width="500" height="500"></canvas><br>
<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader"/>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
function draw() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var pos = getMousePos(canvas, event);
console.log(pos);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
ctx.strokeStyle = 'red';
}
function getMousePos(canvas, event) {
var rect = canvas.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.