Skip to content

Instantly share code, notes, and snippets.

@abcang
Last active August 29, 2015 14:00
Show Gist options
  • Save abcang/3a18e774ec1ebacfd1f7 to your computer and use it in GitHub Desktop.
Save abcang/3a18e774ec1ebacfd1f7 to your computer and use it in GitHub Desktop.
半透明で線を引くやつ
var last_image, pos, down = false;
var canvas;
var ctx = canvas.getContext('2d');
var getPos = function(evt) {
var rect = canvas.getBoundingClientRect();
return {
x: (evt.clientX - rect.left),
y: (evt.clientY - rect.top)
};
};
canvas.addEventListener('mousedown', function (e) {
down = true;
last_image = ctx.getImageData(0, 0, canvas.width, canvas.height);
ctx.beginPath();
pos = getPos(e);
ctx.moveTo(pos.x, pos.y);
}, false);
window.addEventListener('mousemove', function (e) {
if (!down) return;
ctx.putImageData(last_image, 0, 0);
pos = getPos(e);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
}, false);
window.addEventListener('mouseup', function (e) {
if (!down) return;
ctx.putImageData(last_image, 0, 0);
pos = getPos(e);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
ctx.closePath();
down = false;
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment