I'am very new at this and I'm trying to create a signature drawing program in html, canvas and javascript.
Im trying to get the clear button working with this function;
function clearCanvas() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
But it does not seem to work. I don't really know where in the js script to put the function for it to be executed in the html code.
this is the html code:
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="uppgift-6.js"></script>
<title>Uppgift6</title>
<style type="text/css">
#canvas { position: relative; }
#bildruta { border: 2px solid #000; }
body {font-family: Calibri}
h2 {font-size: 150%; color: BLACK; background-color: BEIGE; padding: 20px; margin: 5px auto; text-align: center;}
</style>
</head>
<body>
<h2>Signatur</h2>
<div id="canvas">
<canvas id="bildruta" width="600" height="400"></canvas>
</div>
<button type="button" onclick="clearCanvas()"> Clear signature </button>
</body>
</html>
Grateful for all help that i can get!
答案 0 :(得分:1)
您的ID不正确。更改您的ID或更改JS行:
function clearCanvas() {
var canvas = document.getElementById('bildruta'); // that's the correct ID
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
}
它有效。
答案 1 :(得分:1)
var canvas = document.getElementById('canvas')
指向此div <div id="canvas">
而不是你的画布。
它应该是document.getElementById('bildruta')