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>
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
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
未经授权禁止转载,违者必究!