Canvas image data opacity on top of canvas shape

那年仲夏 提交于 2019-12-24 18:31:14

问题


In the following example I've set the opacity of every image pixel to zero. Why isn't the grey background rectangle visible and how can I achieve that? Am I missing something in the rendering process of the shape vs image data?

<!DOCTYPE html>
<meta charset="utf-8">

<script src="https://d3js.org/d3.v4.min.js"></script>

<body>
    <canvas id='myCanvas'></canvas>
</body>

<script type="text/javascript">

    var width = 500;
    var height = 500;

    var canvas = document.getElementById('myCanvas')
    context = canvas.getContext("2d"),

    canvas.width = width;
    canvas.height = height;

    context.fillStyle = "grey";
    context.fillRect(0,0,100,100);

    var imageData = context.createImageData(width, height);

    for (var i = 0, l = 0; i<height; ++i) {
        for (j = 0; j<width; ++j, l += 4) {
            imageData.data[l+0] = Math.round( Math.random() * 255);
            imageData.data[l+1] = Math.round( Math.random() * 255);
            imageData.data[l+2] = Math.round( Math.random() * 255);
            imageData.data[l+3] = 0;
        }

    }

    context.putImageData(imageData, 0, 0);

</script>

回答1:


putImageData will set the pixels on your context with the ones you passed in the ImageData.

If a given pixel is set to transparent in the ImageData, so will it be on the context after you put it.

To avoid this, you can use an ImageBitmap object, that you'll be able to draw on your context like an image,

const ctx = c.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(0,0,30,30);
const iData = ctx.createImageData(300, 150);
// make the noise mostly transparent
iData.data.forEach((d,i,a)=>{
  a[i] = (i+1)%4 ? Math.random() * 255 : Math.random() * 125;
  })
createImageBitmap(iData).then(img => ctx.drawImage(img, 0,0));
<canvas id="c"></canvas>

or use an off-screen canvas :

const ctx = c.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(0,0,30,30);
const iData = ctx.createImageData(300, 150);
// make the noise mostly transparent
iData.data.forEach((d,i,a)=>{
  a[i] = (i+1)%4 ? Math.random() * 255 : Math.random() * 125;
  })

const offCtx = c.cloneNode().getContext('2d'); // an offscreen canvas
offCtx.putImageData(iData, 0,0);
ctx.drawImage(offCtx.canvas, 0,0);
<canvas id="c"></canvas>


来源:https://stackoverflow.com/questions/46011894/canvas-image-data-opacity-on-top-of-canvas-shape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!