したがって、私のコードはテキストを含むhtmlページを表示し、その下に「キャンバスをクリア」ボタンがあり、一度押してキャンバスをクリアし、この空白のキャンバスに描画できるようにします。キャンバスのクリア ボタンが機能しません。一度押しても何も起こりません。キャンバスのクリアを実行するためにコールバックを使用しています.htmlファイルはjavascriptファイルに接続され、新しいクリアされたキャンバスに描画されます。ここでの最初のコードは、.js ファイルも結合されている、クリアされるキャンバスを含む .html ファイルです。
context.Rect(x, y, w, h); を試しました。および canvas.width.canvas.width; どちらも機能していないようです。私はクロムを使用しています
<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