home.

tagged: javascript

Upload muliple file to Cloudinary with multer

Let's say we have some FormData and some files you've found with <input type="file">.

    var formData = new FormData()
    formData.append("name", "hi")
    formData.append("image", file1)
    formData.append("image", file2)

And you send that data up using fetch or similar.
 
Then in your express server, let's setup cloudinary and multier:

const cloudinary = require('cloudinary');
const cloudinaryStorage = require('multer-storage-cloudinary');
const upload = multer({ dest: 'uploads/' })

cloudinary.config({ 
  cloud_name: 'xxx', 
  api_key: 'xxx', 
  api_secret: 'xx' 
});

var parser = multer({ 
  storage: cloudinaryStorage({
    cloudinary: cloudinary,
    folder: 'xxx',
    filename: function (req, file, cb) {
      cb(undefined, file.originalname);
    }
  })
});

We've setup cloudinary and multer with multer-storage-cloudinary.
 
Now let's make the route with the multer middleware.

router.post('/uploadImages', parser.array('image'), (req, res, next) => {
  console.log(req.files)
  // req.files will show you the uploaded files
  // and req.body will show you the rest of your form data
  res.json("done")
})

javascript expressjs


Javascript: Showing a notification popup message with the Notification API

You can show a small notification popup with the Notification API.
 
You first do Notification.requestPermission() to ask for permission.
 
Once you've got it, you can make a new Notification object. These have various options but we're just showing some text.
 
You can see the source below and a live example here: https://repl.it/@newfivefour/notification-api?language=html&folderId=

<body>
  
  <button onclick="notify()">Notify me</button>

  <script>

    function notify() {

      if (!("Notification" in window)) {
        alert("This browser does not support system notifications");
      } else {
        Notification.requestPermission()
        .then(function(result) {
          if (result === "granted") {
            new Notification("Hi there!");
          } else {
            console.log("permission was not granted.")
          }
        });
      }
        
    }

  </script>

</body>

javascript notification


Javascript: Connect to mongodb

I'm using 3.1.10 of mongo. And the connection dance has changed a bit.

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, client) {
  client.db("inventory").collection("inventory", function(err, collection) {
    collection.insertOne(
      { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
    )
  });
})

You make the connection as usual, but don't mention the database in the url.
 
Then you connect with the connection url. And that gives you a client object.
 
Then you use that client object to open the database. And use that to open the collection.
 
Then you use a callback and issue your insert commands or whatever in that.

javascript mongo


Javascript: Animate a sprite in canvas

Let's say we have an image like this: http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/images/coin-sprite-animation-sprite-sheet.png
 
It has ten mini-images in it. We're going to show the different images in a sequence to create an animation.
 
But first let's load the image:

// First look at this 
// http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/images/coin-sprite-animation-sprite-sheet.png

var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.src = 'http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/images/coin-sprite-animation-sprite-sheet.png';

img.onload = function() {
  var totalNumberOfFrames = 10 // ten images in the image (see the url above)
  var imageFrameNumber = 0 // This is changed to make the sprite animate  
  var widthOfImage = img.width; // find the width of the image
  var heightOfImage = img.height; // find the height of the image
  var widthOfSingleImage = widthOfImage / totalNumberOfFrames; // The width of each image in the spirite
  

We're getting the width and height of the image once it's loaded. And we're getting the width of a single image in our large tile of images (our sprite above). We set a imageFrameNumber which we'll use next.
 
Next we're going to set a interval. When it's run we're going to clear the screen, then update the imageFrameNumber. We're going to make sure it goes from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and then back to 0 and 1, 2, 3, 4, 5, 6, 7, 8, 9 etc:

  setInterval(function() {
    ctx.clearRect(0, 0, 400, 400)    
    
    // Changes the sprite we look at    
    imageFrameNumber++; 
    // Change this from 0 to 1 to 2 ... upto 9 and back to 0 again, then 1...
    imageFrameNumber = imageFrameNumber % totalNumberOfFrames; 
    
     ...
    );      
  }, 100)

Next, we're going to draw the image we loaded above. When imageFrameNumber is 0 then we'll print the first sprite, and when it's 1 we'll print the second, etc:

    ctx.drawImage(img, 
      imageFrameNumber * widthOfSingleImage, 0, // x and y - where in the sprite
      widthOfSingleImage, heightOfImage, // width and height
      50, 50, // x and y - where on the screen
      widthOfSingleImage, heightOfImage // width and height
    );   

All our code is:

// First look at this 
// http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/images/coin-sprite-animation-sprite-sheet.png

var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.src = 'http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/images/coin-sprite-animation-sprite-sheet.png';

img.onload = function() {
  var totalNumberOfFrames = 10 // ten images in the image (see the url above)
  var imageFrameNumber = 0 // This is changed to make the sprite animate  
  var widthOfImage = img.width; // find the width of the image
  var heightOfImage = img.height; // find the height of the image
  var widthOfSingleImage = widthOfImage / totalNumberOfFrames; // The width of each image in the spirite
  
  setInterval(function() {
    ctx.clearRect(0, 0, 500, 500)    
    
    imageFrameNumber++; // changes the sprite we look at
    imageFrameNumber = imageFrameNumber % totalNumberOfFrames; // Change this from 0 to 1 to 2 ... upto 9 and back to 0 again, then 1...
    
    ctx.drawImage(img, 
      imageFrameNumber * widthOfSingleImage, 0, // x and y - where in the sprite
      widthOfSingleImage, heightOfImage, // width and height
      50, 50, // x and y - where on the screen
      widthOfSingleImage, heightOfImage // width and height
    );      
  }, 100)  
  
}

javascript canvas


Javascript: Collision detection in canvas

Previously we created a player on the screen and created obstacles:

var canvas = document.querySelector("canvas")
var context = canvas.getContext("2d");
var obstacles = [{width: 30, height: 30, x: canvas.width - 110, y:110}];
var player = {width: 30, height: 30, x: 0, y:100, speedX: 0.0, speedY: 0.0};
var frame = 0

function updateGameArea() {
    frame++
    context.clearRect(0, 0, canvas.width, canvas.height)
  
    // Add a new obstacle
    if(frame % 100 == 0) obstacles.push({width: 30, height: 30, x: canvas.width, y:canvas.height * Math.random(), speedX: 0.0, speedY: 0.0});
    // Render the obstacles
    obstacles.forEach(o => {
      o.x -= 1
      if(o.hit) context.fillStyle = "red"
      context.fillRect(o.x, o.y, o.width, o.height);    
      context.fillStyle = "black"
    })
  
    // Change the player position
    player.x += player.speedX;
    player.y += player.speedY;
    context.fillRect(player.x, player.y, player.width, player.height);

    requestAnimationFrame(updateGameArea);
}

// When the user pressed the array keys change the speed on the player
window.onkeydown = function(event) {
  event.preventDefault() // stop the arrow keys scrolling the page
  if(event.keyCode == 40) { // down
    player.speedY += 1
  } else if(event.keyCode == 38) { // up
    player.speedY -= 1
  } else if(event.keyCode == 39) { // right 
    player.speedX += 1
  } else if(event.keyCode == 37) { // left
    player.speedX -= 1        
  } 
}

// When the use releases the key, stop the speed and thus position movement
window.onkeyup = function(event) {
  event.preventDefault() // stop the arrow keys scrolling the page
  player.speedX = 0
  player.speedY = 0
}

requestAnimationFrame(updateGameArea);

We're going to use a function that detects if a box (somethig with width, height, x and y properties) is touching another:

function hasHit(box1, box2) {
  var box1Right = box1.x + box1.width
  var box1Bottom = box1.y + box1.height  
  var box2Right = box2.x + box2.width
  var box2Bottom = box2.y + box2.height  
  
  if(box1Right > box2.x && box2Right > box1.x && 
    box1Bottom > box2.y && box2Bottom > box1.y) return true;
  else return false;
}

In the update function, we're going to look at all the obstacles, and check that against our player. If collide, we set a 'hit' property on our obstacle object:

obstacles.forEach(o => {
  if (hasHit(player, o)) {
    o.hit = true;
  }
});

And we'll change our code that renders the obstacles, to do something if 'hit' is true:

obstacles.forEach(o => {
  o.x -= 1
  if(o.hit) context.fillStyle = "red"
  context.fillRect(o.x, o.y, o.width, o.height);    
  context.fillStyle = "black"
})

Our full code is:

var canvas = document.querySelector("canvas")
var context = canvas.getContext("2d");
var obstacles = [{width: 30, height: 30, x: canvas.width - 110, y:110}];
var player = {width: 30, height: 30, x: 0, y:100, speedX: 0.0, speedY: 0.0};

var frame = 0
function updateGameArea() {
    frame++
    context.clearRect(0, 0, canvas.width, canvas.height)
  
    // render the obstacles
    if(frame % 100 == 0) obstacles.push({width: 30, height: 30, x: canvas.width, y:canvas.height * Math.random(), speedX: 0.0, speedY: 0.0});
    obstacles.forEach(o => {
      o.x -= 1
      if(o.hit) context.fillStyle = "red"
      context.fillRect(o.x, o.y, o.width, o.height);    
      context.fillStyle = "black"
    })
  
    // change the player
    player.x += player.speedX;
    player.y += player.speedY;
    context.fillRect(player.x, player.y, player.width, player.height);
  
    // collision detection
    obstacles.forEach(o => {
      if ( hasHit(player,o) ) {
        o.hit = true;
      }
    });

    requestAnimationFrame(updateGameArea);
}


function hasHit(box1, box2) {
  var box1Right = box1.x + box1.width
  var box1Bottom = box1.y + box1.height  
  var box2Right = box2.x + box2.width
  var box2Bottom = box2.y + box2.height  
  
  if(box1Right > box2.x && box2Right > box1.x && 
    box1Bottom > box2.y && box2Bottom > box1.y) return true;
  else return false
}

// When the user pressed the array keys change the speed on the player
window.onkeydown = function(event) {
  event.preventDefault() // stop the arrow keys scrolling the page
  if(event.keyCode == 40) { // down
    player.speedY += 1
  } else if(event.keyCode == 38) { // up
    player.speedY -= 1
  } else if(event.keyCode == 39) { // right 
    player.speedX += 1
  } else if(event.keyCode == 37) { // left
    player.speedX -= 1        
  } 
}

// When the use releases the key, stop the speed and thus position movement
window.onkeyup = function(event) {
  event.preventDefault() // stop the arrow keys scrolling the page
  player.speedX = 0
  player.speedY = 0
}

requestAnimationFrame(updateGameArea);

javascript canvas

Page 3 of 15
prev next