JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdn.rawgit.com/wanadev/snappy-canvas/master/dist/snappy-canvas.js"></script>
<div>Scroll/Drag the canvas</div>
CSS
html, body {
font-family: sans-serif;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
canvas {
background: #fff;
border: silver solid 1px;
}
JavaScript
// New snappy canvas
var canvas = new SnappyCanvas({
width: 300, // Canvas real width
height: 300, // Canvas real height
contentWidth: 150, // Width at scale 1 (usefull when autoResize = true)
contentHeight: 150, // Height at scale 1 (usefull when autoResize = true)
globalScale: 1, // Initial scale of the snappy context (default 1)
globalTranslationX: 0, // Initial translation x of the snappy context (default 0)
globalTranslationY: 0, // Initial translation y of the snappy context (default 0)
scaleLineWidth: true, // If true, the snappy context will scale the line width according to scale (default true)
autoResizeCanvas: false // Allow canvas to be resized when `globalScale` changes
});
// Add it to DOM
document.body.appendChild(canvas);
// Play with "snappy" context
var ctx = canvas.getContext("snappy");
ctx.strokeRect(10, 10, 50, 50);
ctx.fillRect(70, 10, 50, 50);
ctx.beginPath();
ctx.arc(35, 95, 25, Math.PI, 2.5 * Math.PI);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(70, 95);
ctx.arcTo(120, 95, 120, 120, 25);
ctx.stroke();
ctx.render();
// Additional js to allow live interactions with the canvas
var _prevX;
var _prevY;
var _isDragging = false;
canvas.onwheel = function(event) {
if (event.deltaY <= 0) {
ctx.globalScale *= 1.1;
} else {
ctx.globalScale /= 1.1;
}
};
canvas.onmousedown = function() {
_isDragging = true;
};
document.onmouseup = function() {
_isDragging = false;
};
document.onmousemove = function(event) {
if (_isDragging) {
var deltaX = event.pageX - _prevX;
var deltaY = event.pageY - _prevY;
ctx.globalTranslationX += deltaX / ctx.globalScale;
ctx.globalTranslationY += deltaY / ctx.globalScale;
}
_prevX = event.pageX;
_prevY = event.pageY;
};