logo
down
shadow

HTML5 canvas scroll-based animation engaging and disengaging


HTML5 canvas scroll-based animation engaging and disengaging

By : Khaled Alburaihi
Date : November 22 2020, 02:42 PM
like below fixes the issue jsFiddle : https://jsfiddle.net/jvLk0vhp/1/
javascript :
code :
var images = new Array();
var currentLocation = 0;
var totalImages = 7;

for (var i = 0; i < totalImages; i++) {
    var img = new Image;
    switch (i) {
        case 0:
            img.src = "http://img.pokemondb.net/sprites/black-white/normal/mewtwo.png";
            break;
        case 1:
            img.src = "http://img.pokemondb.net/sprites/black-white/normal/keldeo-ordinary.png";
            break;
        case 2:
            img.src = "http://img.pokemondb.net/sprites/black-white/normal/darkrai.png";
            break;
        case 3:
            img.src = "http://floatzel.net/pokemon/black-white/sprites/images/5.png";
            break;
        case 4:
            img.src = "http://vignette1.wikia.nocookie.net/capx/images/0/03/001.png/revision/latest?cb=20140322003659";
            break;
        case 5:
            img.src = "http://img.pokemondb.net/sprites/black-white/normal/absol.png";
            break;
        case 6:
            img.src = "http://img.pokemondb.net/sprites/black-white/normal/dewgong.png";
            break;
        case 7:
            img.src = "http://orig05.deviantart.net/e770/f/2013/008/c/6/froakie_by_baconboy914-d5qvrjo.gif";
            break;
    }

    images.push(img);
}

var c = document.getElementById("background");
var ctx = c.getContext("2d");

var mouseWheel = function () {
    window.addEventListener('mousewheel', function (e) {
        e.preventDefault(); // No scroll

        // The following equation will return either a 1 for scroll down
        // or -1 for a scroll up
        var delta = Math.max(-1, Math.min(1, e.wheelDelta));

        // This code mostly keeps us from going too far in either direction
        if (delta == -1) currentLocation += 1;
        if (delta == 1) currentLocation -= 1;
        if (currentLocation < 0) currentLocation = 0;
        if (currentLocation >= (totalImages - 1)) currentLocation = (totalImages - 1);
        console.log("Current location " + currentLocation);

        // See below for the details of this function
        setImage(currentLocation);
    });
}

var setImage = function (newLocation) {
    // drawImage takes 5 arguments: image, x, y, width, height
    ctx.fillRect(0, 0, c.width, c.height);
    ctx.drawImage(images[newLocation], 0, 0, 150, 150);
}

images[0].onload = function () {
    ctx.fillRect(0, 0, c.width, c.height);
    ctx.drawImage(images[currentLocation], 0, 0, 150, 150);
    mouseWheel();
};
var images = new Array();
var currentLocation = 0;
var totalImages = 7;
var div1 = document.getElementById("id_1");
var div2 = document.getElementById("id_2");
var div3 = document.getElementById("id_3");

div2.style.display = "none";
div3.style.display = "none";

for (var i = 0; i < totalImages; i++) {
    var img = new Image;
    switch (i) {
        case 1:
            img.src = "http://img.pokemondb.net/sprites/black-white/normal/keldeo-ordinary.png";
            break;
        case 2:
            img.src = "http://img.pokemondb.net/sprites/black-white/normal/darkrai.png";
            break;
        case 3:
            img.src = "http://floatzel.net/pokemon/black-white/sprites/images/5.png";
            break;
        case 4:
            img.src = "http://vignette1.wikia.nocookie.net/capx/images/0/03/001.png/revision/latest?cb=20140322003659";
            break;
        case 5:
            img.src = "http://img.pokemondb.net/sprites/black-white/normal/absol.png";
            break;
        case 6:
            img.src = "http://img.pokemondb.net/sprites/black-white/normal/dewgong.png";
            break;
    }

    images.push(img);
}

var c = document.getElementById("background");
var ctx = c.getContext("2d");

var mouseWheel = function () {
    window.addEventListener('mousewheel', function (e) {
        e.preventDefault(); // No scroll

        // The following equation will return either a 1 for scroll down
        // or -1 for a scroll up
        var delta = Math.max(-1, Math.min(1, e.wheelDelta));

        // This code mostly keeps us from going too far in either direction
        if (delta == -1) currentLocation += 1;
        if (delta == 1) currentLocation -= 1;
        if (currentLocation < 0) currentLocation = 0;
        if (currentLocation >= (totalImages - 1)) currentLocation = (totalImages - 1);
        console.log("Current location " + currentLocation);

        // See below for the details of this function
        setImage(currentLocation);
    });
}

var setImage = function (newLocation) {
    // drawImage takes 5 arguments: image, x, y, width, height
    if (newLocation == 0) {
        div1.style.display = "block";
        div2.style.display = "none";
        div3.style.display = "none";
    } else if (newLocation == (totalImages - 1)) {
        div1.style.display = "none";
        div2.style.display = "none";
        div3.style.display = "block";
    } else {
        div1.style.display = "none";
        div2.style.display = "block";
        div3.style.display = "none";

        ctx.fillRect(0, 0, c.width, c.height);
        ctx.drawImage(images[newLocation], 0, 0, 150, 150);
    }
}


ctx.fillRect(0, 0, c.width, c.height);
ctx.drawImage(images[currentLocation], 0, 0, 150, 150);
mouseWheel();


Share : facebook icon twitter icon
html5 canvas scroll

html5 canvas scroll


By : user2862082
Date : March 29 2020, 07:55 AM
seems to work fine It is possible, though probably ugly.
I'll take your question literally...
code :
var canvas = document.createElement('canvas'),

    context = canvas.getContext('2d');

    // Draw whatever on your canvas

var marquee = document.createElement('marquee');

marquee.appendChild(canvas);

document.body.appendChild(marquee);
HTML5 animation - Canvas or DOM?

HTML5 animation - Canvas or DOM?


By : user3870512
Date : March 29 2020, 07:55 AM
I hope this helps you . Here are some "pro" canvas arguments:
The nice fact about canvas is that can be 2D accelerated and you can obtain high fps. Also the problem with DOM is that you are limited to rectangle shape only. All modern browsers have nice canvas support so if you are not limited by legacy system it makes more sense to use canvas
Path based animation in html5 canvas

Path based animation in html5 canvas


By : JMac
Date : March 29 2020, 07:55 AM
will help you I am creating a project that will allow you draw a canvas path and then animate anything else you draw along the path and then export the code for use in your own projects. Paths are built from joining cubic Bezier curves. A first version is available at http://canvimation.github.com/ with source code at https://github.com/canvimation/canvimation.github.com and help files at https://sites.google.com/site/canvimationhelp/.
I am currectly rewriting the code to make it more understandable and robust (stage 1 branch) but have not got to rewriting the animation sections yet. If any of the code is useful to you then you are welcome. Probable useful files are alongpath.js and buildmenu.js
HTML5 Canvas scroll lag

HTML5 Canvas scroll lag


By : Ivan Bačić
Date : March 29 2020, 07:55 AM
Any of those help The problem is in the way you are using the canvas. You should not create a canvas larger than can be displayed on the screen. You just overwork your rendering code if you do.
The flickering is due to you trying to fit the canvas pixels at fractions of a pixel. If you set the camera position to x = 100.5 pixel the display can not physically move the display pixels by 1/2 so it does its best to interpolate the canvas pixels to fit the display pixels. The result is flickering.
code :
//adds or removes keys from keyDown on keydown or keyup
function keyEvent(e) {
  keyDown[e.keyCode] = e.type === "keydown"
}
document.addEventListener("keydown", keyEvent);
document.addEventListener("keyup", keyEvent);

requestAnimationFrame(main);
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const wrapper = document.getElementById("wrapper");
var then;
const framesPerSecond = 30;
var counter = 1000 / framesPerSecond;
var delta = 0;
var friction = 0.9;
const keyDown = {};

function main(time) {
  if (then === undefined) {
    then = time
  }
  delta += time - then;
  then = time;

  if (delta >= counter) {
    delta = 0;
    ctx.setTransform(1, 0, 0, 1, 0, 0); // set default transform
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    player.update();

    // set the view to the camera
    ctx.setTransform(1, 0, 0, 1, -player.camX, -player.camY);
    render();
  }

  requestAnimationFrame(main);
}

var player = {
  x: 0,
  y: 115,
  w: 20,
  h: 20,
  velX: 0,
  speed: 3,
  color: "maroon",
  camX: 0,
  camY: 0,
  camOffsetX: 250,
  camOffsetY: 125,

  update() {
    this.velX *= friction
    this.x += 2 * this.velX;
    if (keyDown["37"]) {
      if (this.velX > -this.speed) {
        this.velX--
      }
    }
    if (keyDown["39"]) {
      if (this.velX < this.speed) {
        this.velX++
      }
    }
    this.updateCamera();
  },
  render() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.w, this.h);
  },
  updateCamera() {
    this.camX = this.x + this.w / 2 - this.camOffsetX;
    this.camY = this.y + this.h / 2 - this.camOffsetY;
  }
};


var render = function() {
  player.render();

  //arrow pointing to the problem
  ctx.fillText("<---", player.camX + 10, player.y);
  ctx.fillText("Player X pos : " + player.camX.toFixed(3), player.x, 100);

  //camera bounderies
  ctx.strokeRect(player.x + player.w / 2 - player.camOffsetX, player.y + player.h / 2 - player.camOffsetY, 2 * player.camOffsetX, 2 * player.camOffsetY);

  //sets markers so you can tell your're scrolling.
  ctx.fillText("250 pixels", 250, 10);
  ctx.fillText("500 pixels", 500, 10);
  ctx.fillText("750 pixels", 750, 10);
  ctx.fillText("1000 pixels", 1000, 10);
  ctx.fillText("1250 pixels", 1250, 10);
  ctx.fillText("1500 pixels", 1500, 10);
  ctx.fillText("1750 pixels", 1750, 10);
}
#wrapper {
  width: 500px;
  height: 250px;
  overflow: hidden;
  border: 1px solid cyan;
}
<!-- div is so the canvas can scroll. -->
<div id="wrapper">
  <canvas id="canvas" width="500" height="250"></canvas>
</div>
make canvas scroll-based image sequences animation more smooth

make canvas scroll-based image sequences animation more smooth


By : Harshit Gour
Date : March 29 2020, 07:55 AM
This might help you This happens because the wheel event might fire at a very high rate, higher than your screen refresh rate.
This means that for every frame painted to the screen, you actually painted several frames on the canvas. The browser then has some issues to handle all these requests, and end up creating lag.
code :
var images = new Array();
var currentLocation = 0;
var totalImages = 200;

for (var i = 1; i < totalImages; i++) {
  var img = new Image;
  var slug = '000' + i;
  img.src = 'https://s3.amazonaws.com/clearmotion/hero/high-min/frame' + slug.slice(-3) + '-low.jpg'
  images.push(img);
}

var c = document.getElementById("background");
var ctx = c.getContext("2d");

var mouseWheel = function() {
  var evt = null; // avoids a new 'draw' function generation
  window.addEventListener('wheel', function(e) {
    e.preventDefault(); // No scroll

    if (!evt) { // if set, we already are waiting
      evt = e; // store our event
      requestAnimationFrame(draw); // wait next screen refresh to fire
    }
  });
  // the throttled funtion
  function draw() {
    var e = evt;
    var delta = Math.max(-1, Math.min(1, e.deltaY));
    if (delta == -1) currentLocation += 1;
    if (delta == 1) currentLocation -= 1;
    if (currentLocation < 0) currentLocation = 0;
    if (currentLocation >= (totalImages - 1)) currentLocation = (totalImages - 1);
    setImage(currentLocation);
    evt = null; // so the throttler knows we can kick again
  }
}

var setImage = function(newLocation) {
  if (!images[newLocation]) return;
  ctx.fillRect(0, 0, c.width, c.height);
  ctx.drawImage(images[newLocation], 0, 0, 1000, 1000);
}

images[0].onload = function() {
  ctx.fillRect(0, 0, c.width, c.height);
  ctx.drawImage(images[currentLocation], 0, 0, 1000, 1000);
  mouseWheel();
};
<canvas id="background" width="1000" height="1000"></canvas>
var images = new Array();
var currentLocation = 0;
var totalImages = 200;

for (var i = 1; i < totalImages; i++) {
  var img = new Image;
  var slug = '000' + i;
  img.src = 'https://s3.amazonaws.com/clearmotion/hero/high-min/frame' + slug.slice(-3) + '-low.jpg'
  images.push(img);
}

var c = document.getElementById("background");
var ctx = c.getContext("2d");

var mouseWheel = function() {
  var newLocation = null;
  window.addEventListener('wheel', function(e) {
    e.preventDefault(); // No scroll

    // update our variable at high frequency
    var delta = Math.max(-1, Math.min(1, e.deltaY));
    if (delta == -1) currentLocation += 1;
    if (delta == 1) currentLocation -= 1;
    if (currentLocation < 0) currentLocation = 0;
    if (currentLocation >= (totalImages - 1)) currentLocation = (totalImages - 1);

    if (newLocation === null) { // if set, we already are waiting to draw
      requestAnimationFrame(setImage);
    }
    newLocation = currentLocation;
  });

  function setImage() {
    if (images[newLocation]) {
      ctx.fillRect(0, 0, c.width, c.height);
      ctx.drawImage(images[newLocation], 0, 0, 1000, 1000);
    }
    newLocation = null; // so the throttler knows we can draw again
  }

}


images[0].onload = function() {
  ctx.fillRect(0, 0, c.width, c.height);
  ctx.drawImage(images[currentLocation], 0, 0, 1000, 1000);
  mouseWheel();
};
<canvas id="background" width="1000" height="1000"></canvas>
Related Posts Related Posts :
  • How to multiply each element in an array with a different number (javascript)
  • Constructing a query string for JQuery getJSON for a public API GET request
  • Server side error generating RSS - what to return back to user/RSS reader?
  • ES6 code on Nodejs 4.x : Is V8 4.5 a native JS engine that runs ES6 directly?
  • How to only get new data without existing data from a Firebase?
  • How to set default option d3.js
  • using enum in Javascript for month number against name
  • React component only changes state on second onClick event
  • JavaScript text area: add line break
  • Unobtrusive jQuery unobtrusive validation not showing error spans
  • get the location for objects in a firebase array?
  • Multiple addEventListener not storing unique callbacks
  • JQuery, variable inside function not recognized by action
  • User input in Javascript
  • JavaScript Regex Remove Content from String
  • Is there a way to apply a mask on keydown? (JQuery)
  • Redirect A Live Website Visitor Without Them Refreshing or Clicking anything?
  • Exclude HTML tags when translating with Google Translate API
  • Posting to a ColdFusion function from angularJS
  • How to nullify the fadeout?
  • JS not updating on enquire.js breakpoints
  • AngularFire Check if item of same title exists
  • add names to objects based on object value
  • When do you use "class" versus "id"?
  • Get content of loaded SVG file
  • How to find size of an image file from canvas?
  • ui-sref="articles.view({articleId: article._id})" meaning?
  • How to structure Angular with Highcharts and lots of dynamic data
  • Why does a component class needed to be reopened to specify positional params?
  • Can I disable sorting in dgrid for performance gain?
  • Which tools (that are not plugins) can be used to create animation which can be manipulated at runtime?
  • Boostrap carousel not working
  • Ember controllers in nested routes
  • How to reload ng-include in AngularJS?
  • Add enter on event in javascript
  • How to set different background color for each repeated column of RadioButtonList
  • Angular filter data by date
  • Showing multiple info boxes in Google Maps when pulling from MySQL
  • Cordova event DeviceReady don't work on all pages
  • JavaScript document object lastModified using toLocale string
  • TypeError: $(...).autocomplete is not a function $("#partipnt-name").autocomplete({
  • Javascript isnan issue
  • Change variance on mouse movement
  • Highcharts - set xAxis range when using xAxis Categories?
  • Typeahead 0.11.1 Mouse over and keyboard conflict when viewing dropdown search results
  • How to use data from $http.get after page load in Vue.js?
  • How to test angular promise with Jasmine
  • Conditionally chain functions in JavaScript
  • Using QueryBuilder and getting "QueryBuilder is not defined" error
  • slideToggle with bounce effect not working
  • AngularJS binding two variables together without being told to do so
  • Anchor doesn't work
  • set different values for drop down list if check box checked or unchecked
  • Fullscreen slide-toggle with cookie
  • Set variable if input field contains text
  • signin with Linkedin code give me html validation error
  • how to call a jquery function from a form
  • iron router reload specific header element
  • .submit function not running when invalid with kendo validator
  • How to use bind() in JS object init
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co