【发布时间】:2021-12-12 09:28:41
【问题描述】:
我正在 Django 中进行一个项目,其中我将一个画布元素叠加在另一个上,其功能允许我将鼠标悬停在顶部画布上以显示加载到其下方画布中的图像。该功能运行良好,但它似乎在其他方面造成了严重破坏,即:
-
窗口的宽度和高度大于画布,导致不必要的滚动。我想摆脱这个。
-
我的画布元素周围有一个浅灰色边框,我无法摆脱它。尝试将轮廓和边框设置为无但没有骰子。
-
我也遇到了在窗口中居中画布的问题。
我的直觉告诉我这些问题与我的画布堆栈设置为绝对位置而其父 div 设置为相对位置(这是允许我堆叠画布的功能)这一事实有关,但这只是预感。
我查看了许多其他类似的 SO 问题,但他们的解决方案都不适用于我的代码。任何帮助将不胜感激。谢谢。
window.onload = function() {
//Create Bottom canvas & context
var canvas = document.getElementById('canvas');
var ctxB = canvas.getContext('2d');
//Create Top canvas & context
var canvas2 = document.getElementById('canvas2');
var ctxT = canvas2.getContext('2d');
//Set waterfall image variable
var waterfall = document.getElementById('waterfall');
//Set canvas w&h properties
canvas.width = canvas2.width = .25*waterfall.width;
canvas.height = canvas2.height = .25*waterfall.height;
//Populate Bottom canvas with image
ctxB.drawImage(waterfall, 0, 0, canvas.width, canvas.height);
//Populate Top canvas with white rectangle
ctxT.fillStyle = "white";
ctxT.fillRect(0, 0, canvas2.width, canvas2.height);
//Erase Top canvas to reveal waterfall
canvas2.addEventListener('mousemove', event => {
var x = event.offsetX;
var y = event.offsetY;
const eraseSize = 100;
ctxT.clearRect(x-eraseSize/2, y-eraseSize/2, eraseSize, eraseSize);
})
}
#stack {
position: relative;
}
#stack canvas {
position: absolute;
display: block;
}
<!DOCTYPE html>
{% load static %}
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="{% static 'entrance/entrance.css' %}">
<script src="{% static 'entrance/entrance.js' %}"></script>
</head>
<body>
<p hidden>
<img src="{% static 'entrance/Waterfall.jpg' %}" alt="issue here" id="waterfall" />
</p>
<div id="stack">
<canvas id="canvas"></canvas>
<canvas id="canvas2"></canvas>
</div>
</body>
</html>
【问题讨论】:
-
请提供样式表 "" - 移除灰色边框。将画布放置在容器中以包含容器并为容器 css 提供 height:auto 和 width: 100%;还添加 margin-left: auto;边距右:自动;让一切居中