Last active
December 28, 2015 06:09
-
-
Save tastywheat/7455050 to your computer and use it in GitHub Desktop.
html5 canvas drawing
This file contains 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
var canvas = document.getElementById('canvas'); | |
var context = canvas.getContext("2d"); | |
var started = false; | |
var crayonTextureImage = new Image(); | |
function init () { | |
canvas.addEventListener('mousemove', mousemove, false); | |
canvas.addEventListener('mousedown', mousedown, false); | |
canvas.addEventListener('mouseup', mouseup, false); | |
crayonTextureImage.src = "Penguins.jpg"; | |
crayonTextureImage.onload = function(){ | |
canvas.width = crayonTextureImage.width; | |
canvas.height = crayonTextureImage.height; | |
canvas.style.width = crayonTextureImage.width + 'px'; | |
canvas.style.height = crayonTextureImage.height + 'px'; | |
context.drawImage(crayonTextureImage, 0, 0); | |
context.strokeStyle = "#df4b26"; | |
context.lineJoin = "round"; | |
context.lineWidth = 5; | |
} | |
} | |
function mousedown(e){ | |
var x; | |
var y; | |
if (e.pageX || e.pageY) { | |
x = e.pageX; | |
y = e.pageY; | |
} | |
else { | |
x = e.clientX + document.body.scrollLeft + | |
document.documentElement.scrollLeft; | |
y = e.clientY + document.body.scrollTop + | |
document.documentElement.scrollTop; | |
} | |
x -= canvas.offsetLeft; | |
y -= canvas.offsetTop; | |
if(!started){ | |
context.beginPath(); | |
context.moveTo(x, y); | |
started = true; | |
} | |
} | |
function mouseup(e){ | |
started = false; | |
//context.globalAlpha = 0.4; | |
//context.drawImage(crayonTextureImage, 0, 0, 400, 400); | |
//context.globalAlpha = 1; // No IE support | |
} | |
function mousemove (e) { | |
var x; | |
var y; | |
if (e.pageX || e.pageY) { | |
x = e.pageX; | |
y = e.pageY; | |
} | |
else { | |
x = e.clientX + document.body.scrollLeft + | |
document.documentElement.scrollLeft; | |
y = e.clientY + document.body.scrollTop + | |
document.documentElement.scrollTop; | |
} | |
x -= canvas.offsetLeft; | |
y -= canvas.offsetTop; | |
// The event handler works like a drawing pencil which tracks the mouse | |
// movements. We start drawing a path made up of lines. | |
if (started) { | |
context.lineTo(x, y); | |
context.stroke(); | |
} | |
} | |
function convertToImage(){ | |
var dataURL = canvas.toDataURL(); | |
document.getElementById('canvasImg').src = dataURL; | |
} | |
init(); | |
//<canvas id="canvas" src="imgres1.jpg" style="border:1px solid;"></canvas> | |
//<button onclick="convertToImage()">convert to image</button> | |
//<img id="canvasImg"> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment