Skip to content

Instantly share code, notes, and snippets.

@sgoranson
Created September 5, 2018 08:32
Show Gist options
  • Save sgoranson/416c1be069abccb907c3607af7ae15a6 to your computer and use it in GitHub Desktop.
Save sgoranson/416c1be069abccb907c3607af7ae15a6 to your computer and use it in GitHub Desktop.
interact.js rainbow pixel canvas
<canvas class="rainbow-pixel-canvas"></canvas>
Double tap to clear the canvas
var pixelSize = 16;
interact('.rainbow-pixel-canvas')
.snap({
// snap to the corners of a grid
mode: 'grid',
// specify the grid dimensions
grid: { x: pixelSize, y: pixelSize }
})
.origin('self')
.draggable({
max: Infinity,
maxPerElement: Infinity
})
// draw colored squares on move
.on('dragmove', function (event) {
var context = event.target.getContext('2d'),
// calculate the angle of the drag direction
dragAngle = 180 * Math.atan2(event.dx, event.dy) / Math.PI;
// set color based on drag angle and speed
context.fillStyle = 'hsl(' + dragAngle + ', 86%, '
+ (30 + Math.min(event.speed / 1000, 1) * 50) + '%)';
// draw squares
context.fillRect(event.pageX - pixelSize / 2, event.pageY - pixelSize / 2,
pixelSize, pixelSize);
})
// clear the canvas on doubletap
.on('doubletap', function (event) {
var context = event.target.getContext('2d');
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
});
function resizeCanvases () {
[].forEach.call(document.querySelectorAll('.rainbow-pixel-canvas'), function (canvas) {
canvas.width = document.body.clientWidth;
canvas.height = window.innerHeight * 0.7;
});
}
// interact.js can also add DOM event listeners
interact(document).on('DOMContentLoaded', resizeCanvases);
interact(window).on('resize', resizeCanvases);
interact.maxInteractions(Infinity);
<script src="https://c4d6f7d727e094887e93-4ea74b676357550bd514a6a5b344c625.ssl.cf2.rackcdn.com/interact-1.1.3.min.js"></script>
.rainbow-pixel-canvas {
border: solid 2px gray;
-ms-touch-action: none;
touch-action: none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment