Skip to content

Instantly share code, notes, and snippets.

@jackysee
Created August 12, 2014 09:42
Show Gist options
  • Save jackysee/61267766368e87cb9c4a to your computer and use it in GitHub Desktop.
Save jackysee/61267766368e87cb9c4a to your computer and use it in GitHub Desktop.
canvas load image and draw
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
function loadCanvas(dataURL) {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// load image from data url
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(this, 0, 0);
};
imageObj.src = dataURL;
var mouse = {x: 0, y: 0};
/* Mouse Capturing Work */
canvas.addEventListener('mousemove', function(e) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
var ctx = context;
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'black';
var onPaint = function() {
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};
canvas.addEventListener('mousedown', function(e) {
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
canvas.removeEventListener('mousemove', onPaint, false);
}, false);
}
// make ajax call to get image data url
var request = new XMLHttpRequest();
request.open('GET', 'http://www.html5canvastutorials.com/demos/assets/dataURL.txt', true);
request.onreadystatechange = function() {
// Makes sure the document is ready to parse.
if(request.readyState == 4) {
// Makes sure it's found the file.
if(request.status == 200) {
loadCanvas(request.responseText);
}
}
};
request.send(null);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment