10

How to implement infinite scroll on canvas using paper.js

 3 years ago
source link: https://blog.knoldus.com/how-to-implement-infinite-scroll-on-canvas-using-paper-js/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to implement infinite scroll on canvas using paper.js

Reading Time: 2 minutes

We make drawing on canvas using paper.js. In this blog, i would explain that how can we implement infinite scroll on canvas.

Suppose we have a fixed size canvas :

xxxxxxxxxx
<canvas id="myCanvas" width="2500" height="1000"></canvas>

But we want to implement infinite scroll i.e. we can draw infinite items on canvas using paper.js. As we will either scroll down or scroll up, then it should scroll infinitely.

First of all, we have to detect mouse scroll event. We have to do separate event handling for scroll up and scroll down.
You can use any method to detect mouse scroll. I am using below approach for that :

xxxxxxxxxx
var canvas= document.getElementById("myCanvas");
function mouseDown(e) {
if (parseInt(navigator.appVersion) > 3) {
var evt = e ? e : window.event;
var delta = evt.wheelDelta ? evt.wheelDelta / 120
: evt.detail ? -evt.detail : 0;
/* For canvas scrolling */
if (delta > 0) { // Scroll up
// Perform action for scroll up
} else { // Scroll down
// Perform action for scroll down
}
}
return true;
}
if (parseInt(navigator.appVersion) > 3) {
canvas.onmousewheel = mouseDown;
if (navigator.appName == "Netscape"
&& parseInt(navigator.appVersion) == 4) {
canvas.captureEvents(Event.MOUSEDOWN);
}
}

Now we will create a paper.js scope :

xxxxxxxxxx
var scope = new paper.PaperScope();
var canvas= document.getElementById("myCanvas");
scope.setup(canvas);

As we know, paper.js scope has one project and its view, by default. Whatever items we draw, it holds by the project and using view, we can handle drawing and user interaction with mouse and keyboard.
So for infinite scrolling, we have to play with view.

For scroll Up :

xxxxxxxxxx
// Perform action for scroll up
scope.view.scrollBy(new scope.Point(0,-100));

As we scroll up, view should also be scroll by (0,100) i..e x = 0, y = 100. You can change the y value as per your need.

For scroll down :

xxxxxxxxxx
// Perform action for scroll down
scope.view.scrollBy(new scope.Point(0,100));

As we scroll down, view should also be scroll by (0,-100) i..e x = 0, y = -100. You can change the y value as per your need.
Its done. Now you will be able to get infinite scrolling.

Cheers !!!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK