javascript - 我正在尝试使用 javascript 创建一个绘图应用程序,但它应该发生的画布元素没有响应。我的代码有什么问题?
问题描述
这应该是站点内的一个 javascript 绘图应用程序。用户应该能够简单地加载站点并能够在画布内绘图。现在,尽管没有错误消息,但画布没有响应……有人发现有什么问题吗?我可能对此太陌生了。
// paint.js
(function () {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
//resizing
//canvas.height = window.innerHeight;
//canvas.width = window.innerWidth;
//variables
var painting = false;
function startPosition(e) {
painting = true;
draw(e);
}
function endPosition() {
painting = false;
context.beginPath();
}
function draw(e) {
if (!painting) return;
context.lineWidth = 7;
context.lineCap = "round";
context.strokeStyle = "green";
context.lineTo(e.clientX, e.clientY);
context.stroke();
context.beginPath();
context.moveTo(e.clientX, e.clientY);
}
//EventListeners
canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mouseup", endPosition);
canvas.addEventListener("mousemove", draw);
})();
@charset "UTF-8";
/* CSS Document */
body {
text-wrap: wrap;
text-align: center;
background: #e0ebdd;
font-family: helvetica;
}
.nav {
width: 50%;
padding: 15px;
margin: auto;
text-align: center;
font-family: Consolas, "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", Monaco, "Courier New", "monospace";
font-size: 20px;
color: black;
}
.nav a {
transition: 0.4s;
}
.nav a:hover {
color:#FFB52A;
font-style: italic;
padding: 10px;
transition: 0.2s;
}
.footer {
clear: both;
}
.info {
margin: auto;
width: 50%;
align-content: center;
text-align: center;
text-size: 16px;
}
.wavingHand {
float: left;
position: relative;
bottom: 100px;
left: 100px;
clear: right;
width: 100px;
padding: 50px;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>draw-and-listen</title>
<link href="grove.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>draw and listen</h1>
<div class="nav">
<a href="artists.html">artists</a>
<a href="draw-and-listen.html">draw and listen</a>
<a href="store.html">store</a>
</div>
<div>
<canvas id="canvas" height="480" width="640" style="border:1px solid #000000; background-color: white;">Please update your browser.</canvas>
<script src="paint.js"></script>
</div>
<a class="aHome" href="index.html"><img src="img/planet-green.png" style="float:right;width:42px;height:42px;" alt="home planet"></a>
<div>
<p style="clear: right;">© 2020</p>
</div>
</body>
</html>
奇怪的是,当我在这里运行它时,它似乎可以工作(虽然鼠标未对齐......)但是当我只是在谷歌浏览器中运行 HTML 时,画布没有响应。
解决方案
实际上,您的代码正在运行,您可以在draw
函数中记录一些内容。问题是(X,Y)坐标。在您的情况下,您可以将画布视口大小和画布元素大小设置为相同的值,以确保鼠标位置不正确。
<canvas id="canvas" height="480" width="640" style="border:1px solid #000000; width: 640px; height:480px;"></canvas>
推荐阅读
- css - 背景响应的问题
- java - 如何在 Java 11 中读取 HttpRequest 的正文?
- javascript - 如何在框架中向此 JavaScript 添加关闭按钮
- swift - Swift - 帮助破译调用堆栈
- azure-devops - Build Artifact 和 Pipeline Artifact 任务有什么区别?
- c# - IIS 上的 ASP.NET Core 应用程序 - 错误堆栈跟踪记录在哪里?
- python - 如何使用 numpy 函数制作此列表
- python - 反序列化带有嵌入引号的 JSON
- vba - 如何编写 VBA 宏以将重复任务添加到附加到 Azure DevOps 的项目中的 PBI
- java - Jacoco 覆盖率 0.0