caleb531 / jcanvas

A jQuery plugin that makes the HTML5 canvas easy to work with.
https://projects.calebevans.me/jcanvas/
MIT License
626 stars 192 forks source link

Draw transparent image #340

Closed marcoschwartz closed 6 years ago

marcoschwartz commented 6 years ago

Hello,

I am trying to draw images with a different opacity, I thought the right method was to call a function when the load event is triggered, and then use setPixels(). However, i can't seem to figure out how to pass the position & dimensions of the image for the setPixels function. Also not sure what to pass to setPixels to make the image transparent. Am I missing something? Thanks!

caleb531 commented 6 years ago

@marcoschwartz The load()callback accepts an object of the image properties as its only argument. You can use this object to grab the x, y, width, and height properties.

Here's an example you can run in the jCanvas Sandbox. Please let me know if you have any questions.

function invert(layer) {
  $(this).setPixels({
    x: layer.x, y: layer.y,
    width: layer.width, height: layer.height,
    // loop through each pixel
    each: function(px) {
      px.r = 255 - px.r;
      px.g = 255 - px.g;
      px.b = 255 - px.b;
    }
  });
}

$('canvas').drawImage({
  layer: true,
  source: 'images/fish.jpg',
  x: 150, y: 100,
  // Invert image color when image loads
  load: invert
});
marcoschwartz commented 6 years ago

Thanks so much, that works now!