简体   繁体   English

不透明度不应用JavaScript画布

[英]Opacity Not Applying JavaScript Canvas

I am calling my method drawInventory() when my mouse moves and when I press i. 当鼠标移动并按i时,我正在调用方法drawInventory()。

I set the opacity at the start of the drawInventory Method: 我在drawInventory方法的开头设置不透明度:

 function drawInventory() {
inventoryCtx.fillStyle = "rgba(0, 0, 0, 0.7)";
inventoryCtx.fillRect(10, 10, invWidth-20, invHeight-20);
 }

When I move the mouse, the opacity stays at .7 correctly, however after pressing i, the opacity decreases. 当我移动鼠标时,不透明度正确保持在0.7,但是按i后,不透明度会降低。

Here is the method I call upon the i keypress: 这是我在i按键上调用的方法:

    function toggleInventory() {
    if(!showInventory) {
        showInventory = true;
        $("#inventoryCanvas").removeClass("hideClass");
        drawInventory();
        $("#inventoryCanvas").fadeIn(1);
    }
    else {
        $("#inventoryCanvas").fadeOut(100);
        showInventory = false;
    }
};

The strange part is, the first time after refreshing the page and pressing i the opacity is there. 奇怪的是,刷新页面并按i后第一次出现不透明度。 If I press i twice, it comes back with even higher opacity (darker) then the next time it is completely dark. 如果我按两次i,它会以更高的不透明度(较暗)返回,然后在下一次完全黑暗时返回。 I do not know why it is losing opacity each time when I am calling the same method. 我不知道为什么每次调用同一方法时它都会失去不透明度。

Note: I've tried inventoryCtx.globalAlpha, it does not change the issue. 注意:我已经尝试了ventureCtx.globalAlpha,它不会改变问题。

Any help is appreciated. 任何帮助表示赞赏。

A canvas object is an image and is initially completely transparent. canvas对象是图像,最初是完全透明的。

When you draw on it using the context however the pixels are changed to reflect your drawing. 当您使用上下文在其上绘制时,像素会更改以反映您的绘制。

If you draw a second time on it you will start from what is currently on the canvas and that's why it seems to you that the opacity is not applied; 如果您第二次在其上绘制,将从当前画布上的内容开始,这就是为什么在您看来未应用不透明度的原因; the reason is that it's applied but on pixels that are already not completely transparent. 原因是它已应用,但已应用于不完全透明的像素。

Note that hiding and showing the element doesn't wipes off its content. 请注意,隐藏和显示元素不会擦除其内容。 Each canvas instance will remember the value of its pixels even if you move it around the DOM tree. 每个画布实例都会记住其像素值,即使您在DOM树中移动它也是如此。

To keep repeatable results when drawing you need to clear the canvas on starting of the paint procedure using 为了在绘制时保持可重复的结果,您需要在开始绘制过程时使用以下方法清除画布

canvas.clearRect(0, 0, canvas.width, canvas.height);

or by setting the canvas object size with 或通过设置画布对象的大小

canvas.width = canvas.width;

as resizing a canvas has the documented side effect of clearing its content even if the size remains exactly the same. 因为调整画布的大小具有记录的副作用,即使大小保持完全相同,清除其内容也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM