How to set z-index order in Canvas using javascript All In One
How to set z-index order in Canvas using javascript All In One
如何使用 javascript 在 Canvas 中设置 z-index 顺序
globalCompositeOperation
// 全局作用域 global scope
const cvs = document.querySelector("#canvas");
const ctx = canvas.getContext('2d');
// 设置 z-index 顺序
ctx.globalCompositeOperation='destination-over';
ctx.strokeStyle = "green";
ctx.strokeRect(10, 10, 110, 110);
demos
- canvas 绘制的元素,默认 z-index 递增,即后面的大于前面的;
- 现象,如元素存在重叠部分,后面的回覆盖掉前面的; (可能在某些使用场景中是一个 bug ❌)
- 使用
globalCompositeOperation
属性可以,设置 z-index 的顺序; ✅
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="author" content="xgqfrms">
<meta name="generator" content="VS code">
<title>WebGPU</title>
<style lang="css">
#canvas {
box-sizing: border-box;
outline: 1px dashed pink;
}
</style>
</head>
<body>
<header>
<h1>WebGPU</h1>
</header>
<main id="root">
<!-- <canvas id="canvas">
注意:canvas 元素的默认尺寸为 300x150 像素
</canvas> -->
<canvas id="canvas" width="512" height="512"></canvas>
<script>
// 全局作用域 global scope
const cvs = document.querySelector("#canvas");
const ctx = canvas.getContext('2d');
// 设置 z-index 顺序
ctx.globalCompositeOperation='destination-over';
ctx.strokeStyle = "green";
ctx.strokeRect(10, 10, 110, 110);
</script>
<script type="module">
// 块级作用域 block scope
const canvas = document.querySelector("#canvas");
// Your WebGPU code will begin here!
const context = canvas.getContext('2d');
context.fillStyle = "red";
context.fillRect(100, 100, 200, 200);
</script>
</main>
<footer>
<p>copyright© xgqfrms 2022</p>
</footer>
</body>
</html>
refs
https://stackoverflow.com/questions/9165766/html5-canvas-set-z-index
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17621995.html
未经授权禁止转载,违者必究!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
2022-08-12 程序员如何挑选和购买一款高性价比的电动升降桌 All In One
2022-08-12 LeetCode 旋转数组算法题解 All In One
2022-08-12 macOS run VSCode from terminal All In One
2022-08-12 小甲鱼 All In One
2021-08-12 vue computed pass params All In One
2020-08-12 wifi IP address scanner on macOS All In One
2020-08-12 算法的时间复杂度 & 性能对比