Create A Spotlight Effect using Canvas and Scrawl.js

Category: Image , Javascript | September 17, 2014
Author:kaliedarik
Views Total:2,586 views
Official Page:Go to website
Last Update:September 17, 2014
License:MIT

Preview:

Create A Spotlight Effect using Canvas and Scrawl.js

Description:

Makes use of Scrawl.js library to convert an image into a canvas object and to add a spotlight effect over the canvas using gradient.

How to use it:

Insert an image into your web page.

<img src="1.jpg" id="demo" class="image-demo">

Make the image invisible and fix positioned in CSS.

img {
  position: fixed;
  visibility: hidden;
}

Create a canvas element over the image.

<canvas id="mycanvas" width="750" height="375"></canvas>

Include the latest Scrawl.js Html5 canvas library at the end of the document.

<script src="https://scrawl.rikweb.org.uk/js/scrawlCore-min.js"></script>

The Javascript to create a spotlight effect on the image.

var mycode = function(){
  //define variables
  var myPad = scrawl.pad.mycanvas,
    here,
    gradient,
    myGloom,
    mySpotlight;
  //import images into scrawl library
  scrawl.getImagesByClass('demo092');
  //define designs (gradient)
  gradient = scrawl.newRadialGradient({
    name: 'spotlight',
    startRadius: 50,
    endRadius: 150,
    color: [
      {color: 'rgba(0,0,0,0)', stop: 0},
      {color: 'rgba(0,0,0,0.8)', stop: 1},
    ],
  });
  //define sprites
  scrawl.newPicture({
    source: 'flower',
    width: 750,
    height: 500,
  });
  myGloom = scrawl.newBlock({
    name: 'gloomy',
    fillStyle: 'rgba(0,0,0,0.8)',
    method: 'fill',
    width: 750,
    height: 375,
    order: 1,
  });
  mySpotlight = myGloom.clone({
    name: 'shiny',
    fillStyle: 'spotlight',
  });
  //animation object
  scrawl.newAnimation({
    fn: function(){
      here = myPad.getMouse();
      if(here.active) {
        gradient.set({
          startX: here.x,
          startY: here.y,
          endX: here.x,
          endY: here.y,
        });
        myGloom.set({visibility: false});
        mySpotlight.set({visibility: true});
      }
      else {
        myGloom.set({visibility: true});
        mySpotlight.set({visibility: false});
      }
      scrawl.render();
    },
  });
};
scrawl.loadModules({
  path: 'http://scrawl.rikweb.org.uk/js/',
  modules: ['block', 'images', 'animation'],
  callback: function(){
    window.onload = function(){
      scrawl.init();
      mycode();
    };
  },
});

You Might Be Interested In:


Leave a Reply