首页 > 解决方案 > 我正在尝试使用 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 时,画布没有响应。

标签: javascripthtmlcanvas

解决方案


实际上,您的代码正在运行,您可以在draw函数中记录一些内容。问题是(X,Y)坐标。在您的情况下,您可以将画布视口大小和画布元素大小设置为相同的值,以确保鼠标位置不正确。

<canvas id="canvas" height="480" width="640" style="border:1px solid #000000; width: 640px; height:480px;"></canvas>

推荐阅读