簡體   English   中英

Javascript/HTML 中的清除畫布按鈕不起作用

[英]Clear canvas button in Javascript/HTML not working

所以我的代碼顯示了一個帶有一些文本的 html 頁面,然后在它下面有一個“清除畫布”按鈕,我想在按下后清除畫布,然后能夠在這個空白畫布上繪圖。 我的透明畫布按鈕不起作用,按下后它什么也沒做。 我正在使用回調來執行清除畫布,並將 html 文件連接到一個 javascript 文件,然后在新清除的畫布上繪制內容。 此處的第一個代碼是帶有正在清除的畫布的 .html 文件,該文件還加入了 .js 文件。

我試過 context.Rect(x, y, w, h); 和 canvas.width.canvas.width; 而且似乎都不起作用。 我正在使用 Chrome

  <html><head></head>
   <h3>  </h3>
   <body >
    <canvas id="main" width="300" height="500"></canvas>

   <script>
   var canvas = document.getElementById("main");
  var context = canvas.getContext('2d');
   context.fillStyle = "#008000";
  context.rect(0,0,300,300);
 context.fill();

 </script>
  </body></html>

  <!DOCTYPE html>
  <html>
  <head>
  <meta name="viewport" content="user-scalble=no,initial-scale=1.0,maximum-scale=1.0" />
 <style>
 body { padding:10px; margin:0px; background-color: #FF9; }
 #main { margin: 10px auto 0px auto; }
 </style>
 <script src=".js"></script>
</head>
<body >
 <button id="clear">Clear Canvas</button><br>
<canvas id="main" width="300" height="500"></canvas>
 </body>
  </html>
   //end of .html file

// JavaScript Document
 // wait until window is fully loaded into browser
 window.onload = function() 
 {
  // so smart phone does not move/resize image when touched
 document.ontouchmove = function(e)
  { 
  e.preventDefault(); 
   }
  var canvas = document.getElementById('main');
  // Number of pixels used by the Clear button above canvas 
  var canvasTop = canvas.offsetTop;
  var context = canvas.getContext('2d');
  var lastX, lastY;
  context.strokeStyle = #FA8072;
  context.lineCap = 'round';
  context.lineJoin = 'round'; 
  context.lineWidth = 8;
   context.fill();
  // Function to Clear the Canvas
    function clear() 
   { 
      context.fillStyle = 'blue'
     context.rect( 0, 0, 300, 500);
    context.fill();
     }
    // Function Dot (to start a new line or just a point)
      function dot(x,y) 
  { 
    context.beginPath();
   context.fillStyle = '#D2691E';
   // draw tiny circle
   context.arc(x,y,1,0, Math.PI*2, true); 
   context.fill();
  context.closePath();
  }
  // Handle the Clear button
   var clearButton = document.getElementById('clear');
  // set callback funct. clear()for future touch events
 clearButton.onclick = clear;
 clear(); // do a clear canvas now
 } // end window.onload

你在這一行有一個錯字:

context.strokeStyle = #FA8072;

你需要報價:

context.strokeStyle = '#FA8072';

修復后它似乎可以工作:http: //jsfiddle.net/eMSXU/

(順便說一句,您可能想按小提琴中的“整理”按鈕來查看您的代碼應該如何縮進...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM