Scrollable canvas inside div

css, html, javascript, jquery

Solution

Here is a demo of using an oversize canvas, and scrolling with mouse movements by adjusting the CSS margin: https://jsfiddle.net/ax7n8944/

HTML:

<div id="canvasdiv" style="width: 500px; height: 250px; overflow: hidden">
    <canvas id="canvas" width="10000px" height="250px"></canvas>
</div>

JS:

var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
var dragging = false;
var lastX;
var marginLeft = 0;

for (var i = 0; i < 1000; i++) {
    context.beginPath();
    context.arc(Math.random() * 10000, Math.random() * 250, 20.0, 0, 2 * Math.PI, false);
    context.stroke();
} 

canvas.addEventListener('mousedown', function(e) {
    var evt = e || event;
    dragging = true;
    lastX = evt.clientX;
    e.preventDefault();
}, false);

window.addEventListener('mousemove', function(e) {
    var evt = e || event;
    if (dragging) {
        var delta = evt.clientX - lastX;
        lastX = evt.clientX;
        marginLeft += delta;
        canvas.style.marginLeft = marginLeft + "px";
    }
    e.preventDefault();
}, false);

window.addEventListener('mouseup', function() {
    dragging = false;
}, false);

Problem

I have a html5 canvas. I need to show the fixed portion of it in the div(`Div1`). When I swipe inside `Div1`, I need to scroll the canvas. So as I scroll, I'll see corresponding part of the canvas. I tried something like this: ``` <div id="Div1" style=" float: left; width: 50px; overflow:hidden; "> <canvas id="myCanvas1" width="200px" style="border: 1px solid #ff0000; position: absolute;"> </canvas> </div> ``` jsFiddled here

Original source