javascript - 不同画布的不同 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;
}
解决方案
问题是您将文本覆盖的上下文设置为画布上下文,修复将更改为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>
希望这可以帮助 :)
推荐阅读
- python - 从存储在数据框列中的多个 url 中提取数据
- memory-management - 如何在内核中从一个物理页面复制到另一个物理页面
- c++ - 为什么析构函数以相反的顺序调用?
- javascript - Fabric.js 中缺少过滤器
- okta - 有没有办法限制 Okta 令牌权限?
- list - Ansible 使用 with_items 将项目分配给变量
- perl - Devel::Cover - 无法将分支标记为可发现
- text - 清除文本中位置不正确的 CR+LF
- python - 启动应用程序时 Py2App PIL Image 错误
- python - WebScraping & python:在 html 中渲染 javascript?