Skip to content

Instantly share code, notes, and snippets.

@ezzaouia
Last active November 2, 2017 15:32
Show Gist options
  • Save ezzaouia/60e849cefc9c1fb62d1315fef4b9e8ad to your computer and use it in GitHub Desktop.
Save ezzaouia/60e849cefc9c1fb62d1315fef4b9e8ad to your computer and use it in GitHub Desktop.
canvas :/
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g="
crossorigin="anonymous"></script>
<style>
#canvas {
border: 1px solid red;
}
#canvas2 {
border: 1px solid blue;
}
#canvas3 {
border: 1px solid orange;
}
</style>
</head>
<body>
<canvas id="canvas" width="200" height="500"></canvas>
<canvas id="canvas3" width="200" height="500"></canvas>
<canvas id="canvas2" width="200" height="500"></canvas>
<script>
var layer2 = document.getElementById('canvas3');
var canvas = document.getElementById('canvas');
var canvasPos = canvas.getBoundingClientRect();
$(canvas).mousedown(mouseDown);
$(canvas).mouseup(mouseUp);
$(canvas).mousemove(mouseMove);
var ctx = canvas.getContext('2d');
var dragging = false;
var paths = [];
var layer1, c2, c3;
layer1 = document.getElementById('canvas2');
layer1.width = 200; // same size as the onscreen canvas
layer1.height = 500;
layer2.width = 200; // same size as the onscreen canvas
layer2.height = 500;
c2 = layer1.getContext("2d");
c2.lineCap = "round";
c2.lineJoin = "round";
c2.lineWidth = 16;
c3 = layer2.getContext("2d");
c3.lineCap = "round";
c3.lineJoin = "round";
c3.lineWidth = 16;
function mouseDown(e) {
paths = [];
var pos = getCursorPosition(e);
dragging = true;
paths.push([pos]); // Add new path, the first point is current pos.
}
function mouseUp(e) {
dragging = false;
c3.drawImage(canvas, 0, 0);
}
function mouseMove(e) {
var pos, i;
if (!dragging) {
return;
}
pos = getCursorPosition(e);
paths[paths.length - 1].push(pos); // Append point tu current path.
refresh();
}
function refresh() {
// clear canvas
ctx.clearRect(0, 0, layer1.width, layer1.height);
for (var i = 0; i < paths.length; ++i) {
var path = paths[i];
if (path.length < 1)
continue;
c2.beginPath();
c2.moveTo(path[0].x, path[0].y);
for (var j = 1; j < path.length; ++j) {
c2.lineTo(path[j].x, path[j].y);
}
c2.strokeStyle = 'rgba(0,0,0,0.4)';
c2.stroke();
ctx.drawImage(layer1, 0, 0);
c2.clearRect(0, 0, layer1.width, layer1.height);
}
}
function getCursorPosition(e) {
return {
x: e.clientX - canvasPos.left,
y: e.clientY - canvasPos.top
};
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment