首页 > 解决方案 > 不同画布的不同 globalAlpha

问题描述

我需要我的文本叠加层具有与画布叠加层不同的颜色和不同的 globalAlpha 值。但是,textOverlay是从画布继承属性,我该如何防止这种情况并为每个属性设置不同的属性?

JS代码示例:

function draw(cordOne, cordTwo, cordThree, n) {

  let canvas = document.getElementById("canvas");
  let textOverlay = document.getElementById("text");
  if (canvas.getContext) {
    let context = canvas.getContext("2d");
    let textOverlay = canvas.getContext("2d");

    context.globalAlpha = 0.1;
    context.beginPath();
    context.moveTo(cordOne[0], cordOne[1]);
    context.lineTo(cordTwo[0], cordTwo[1]);
    context.lineTo(cordThree[0], cordThree[1]);
    context.closePath();

    let centerX = (cordOne[0] + cordTwo[0] + cordThree[0]) / 3;
    let centerY = (cordOne[1] + cordTwo[1] + cordThree[1]) / 3;

    textOverlay.font = "20px Arial Black";
    textOverlay.fillText(n, centerX, centerY);

    context.lineWidth = 4;
    context.strokeStyle = "#666666";
    context.stroke();

    // the fill color
    context.fillStyle = "#22234";
    context.fill();
    }
 }

 draw([35, 49], [168, 49], [168, 128], 1);
 draw([35, 49], [140, 49], [140, 115], 2);

HTML:

<html>

<body>
  <div class="stack">
    <canvas id="text" width="1000" height="700">
    </canvas>
    <canvas id="canvas" width="1000" height="700">
    </canvas>
  </div> 
</body>

</html>

CSS:

.stack {
  position: relative;
}
.stack canvas {
  position: absolute;
  left: 0;
  top: 0;
}

标签: javascripthtml5-canvas

解决方案


问题是您将文本覆盖的上下文设置为画布上下文,修复将更改为let textOverlay = canvas.getContext("2d");textOverlay画布let tCtx = textOverlay.getContext("2d");在哪里。textOverlay

例子:

function draw(cordOne, cordTwo, cordThree, n) {

  let canvas = document.getElementById("canvas");
  let textOverlay = document.getElementById("text");
  if (canvas.getContext) {
    let context = canvas.getContext("2d");
    let t = textOverlay.getContext("2d");

    context.globalAlpha = 0.1;
    context.beginPath();
    context.moveTo(cordOne[0], cordOne[1]);
    context.lineTo(cordTwo[0], cordTwo[1]);
    context.lineTo(cordThree[0], cordThree[1]);
    context.closePath();

    let centerX = (cordOne[0] + cordTwo[0] + cordThree[0]) / 3;
    let centerY = (cordOne[1] + cordTwo[1] + cordThree[1]) / 3;

    t.font = "20px Arial Black";
    t.fillText(n, centerX, centerY);

    context.lineWidth = 4;
    context.strokeStyle = "#666666";
    context.stroke();

    // the fill color
    context.fillStyle = "#22234";
    context.fill();
    }
 }

 draw([35, 49], [168, 49], [168, 128], 1);
 draw([35, 49], [140, 49], [140, 115], 2);
.stack {
  position: relative;
}
.stack canvas {
  position: absolute;
  left: 0;
  top: 0;
}
<div class="stack">
    <canvas id="text" width="1000" height="700">
    </canvas>
    <canvas id="canvas" width="1000" height="700">
    </canvas>
  </div> 

希望这可以帮助 :)


推荐阅读