画布形状顶部的画布图像数据不透明度

时间:2017-09-02 08:23:33

标签: javascript canvas

在以下示例中,我将每个图像像素的不透明度设置为零。为什么灰色背景矩形不可见,我怎样才能实现呢?我在形状与图像数据的渲染过程中遗漏了什么吗?

<!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 个答案:

答案 0 :(得分:1)

putImageData会根据您在ImageData中传递的像素设置上下文中的像素。

如果在ImageData中将给定像素设置为透明,则在放置它之后它将在上下文中。

为了避免这种情况,你可以使用一个ImageBitmap对象,你可以在你的上下文中绘制图像,

&#13;
&#13;
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));
&#13;
<canvas id="c"></canvas>
&#13;
&#13;
&#13;

或使用离屏画布:

&#13;
&#13;
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);
&#13;
<canvas id="c"></canvas>
&#13;
&#13;
&#13;