Created
May 7, 2014 14:11
-
-
Save abcang/73fe052384c418e00314 to your computer and use it in GitHub Desktop.
半透明で線を書くやつその2
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 last_image, pos, down = false, last_pos; | |
var myCanvas, mainCanvas; | |
var myCtx = myCanvas.getContext('2d'); | |
var mainCtx = mainCanvas.getContext('2d'); | |
var getPos = function(evt) { | |
var rect = mainCanvas.getBoundingClientRect(); | |
return { | |
x: (evt.clientX - rect.left), | |
y: (evt.clientY - rect.top) | |
}; | |
}; | |
mainCanvas.addEventListener('mousedown', function (e) { | |
down = true; | |
myCtx.clearRect(0, 0, myCanvas.width, myCanvas.height); | |
myCtx.save(); | |
last_image = mainCtx.getImageData(0, 0, mainCanvas.width, mainCanvas.height); | |
last_pos = getPos(e); | |
mainCtx.globalAlpha = myCtx.globalAlpha; | |
myCtx.globalAlpha = 1.0; | |
}, false); | |
window.addEventListener('mousemove', function (e) { | |
if (!down) return; | |
myCtx.beginPath(); | |
myCtx.moveTo(last_pos.x, last_pos.y); | |
last_pos = getPos(e); | |
myCtx.lineTo(last_pos.x, last_pos.y); | |
myCtx.closePath(); | |
myCtx.stroke(); | |
mainCtx.putImageData(last_image, 0, 0); | |
mainCtx.drawImage(myCanvas, 0, 0); | |
}, false); | |
window.addEventListener('mouseup', function (e) { | |
if (!down) return; | |
myCtx.beginPath(); | |
myCtx.moveTo(last_pos.x, last_pos.y); | |
last_pos = getPos(e); | |
myCtx.lineTo(last_pos.x, last_pos.y); | |
myCtx.stroke(); | |
myCtx.closePath(); | |
myCtx.restore(); | |
mainCtx.save(); | |
mainCtx.putImageData(last_image, 0, 0); | |
mainCtx.drawImage(myCanvas, 0, 0); | |
mainCtx.restore(); | |
down = false; | |
}, false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment