How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

前端 未结 8 1130
庸人自扰
庸人自扰 2020-11-27 09:51

Using the HTML5 element, I would like to load an image file (PNG, JPEG, etc.), draw it to the canvas completely transparently, and then fade it i

8条回答
  •  借酒劲吻你
    2020-11-27 10:24

    The post is old so far I'll go with my suggestion. Suggestion is based on pixel manipulation in canvas 2d context. From MDN:

    You can directly manipulate pixel data in canvases at the byte level

    To manipulate pixels we'll use two functions here - getImageData and putImageData

    getImageData function usage:

    var myImageData = context.getImageData(left, top, width, height);

    and putImageData syntax:

    context.putImageData(myImageData, dx, dy); //dx, dy - x and y offset on your canvas

    Where context is your canvas 2d context

    So to get red green blue and alpha values, we'll do the following:

    var r = imageData.data[((x*(imageData.width*4)) + (y*4))];
    var g = imageData.data[((x*(imageData.width*4)) + (y*4)) + 1];
    var b = imageData.data[((x*(imageData.width*4)) + (y*4)) + 2];
    var a = imageData.data[((x*(imageData.width*4)) + (y*4)) + 3];
    

    Where x is x offset, y is y offset on canvas

    So we having code making image half-transparent

    var canvas = document.getElementById('myCanvas');
    var c = canvas.getContext('2d');
    var img = new Image();
    img.onload  = function() {
       c.drawImage(img, 0, 0);
       var ImageData = c.getImageData(0,0,img.width,img.height);
       for(var i=0;i

    You can make you own "shaders" - see full MDN article here

提交回复
热议问题