Welcome back after the holiday season and a very Happy New Year to you all !
Philippe started a new topic with Giving a try at HTML5 canvas and Javascript before the Christmas and year-end holidays started. In the above post we saw how quickly we can build simple HTML5 application to draw planer geometries like Line and Circle using mouse click. Let's add some more fun!
Let's see how we can draw these types of geometric objects from user input and save the resulting geometries as image.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#myCanvas {
border: thin solid;
}
button {
display: block;
width: 100px;
}
#myButtons {
float: down;
}
</style>
<script type="text/javascript">
//
// function
//
function myDrawing(x1, y1, x2, y2) {
// setup the canvas and context
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(x1.value, y1.value);
context.lineTo(x2.value, y2.value);
// Set Line width
context.lineWidth = 5;
// Set Line color
context.strokeStyle = '#fa00ff';
context.stroke();
}
//
// function
//
function saveImage() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
// save canvas image as Data URL
var imageDataURL = canvas.toDataURL("image/png");
// set myCanvasImage image src to dataURL to save it as an Image
document.getElementById('myCanvasImage').src = imageDataURL;
// if you want to show the resulting image
// in the current window replacing everyting then
// use the following code
//window.location = imageDataURL;
}
//
</script>
</head>
<body>
<canvas id="myCanvas" width="450" height="300"
style="border:5px solid #000000;">
Your browser does not support the new HTML5 canvas element.
</canvas>
<img id="myCanvasImage">
<form>
X1: <input type="text" name="x1"> Y1: <input type="text" name="y1"><br>
X2: <input type="text" name="x2"> Y2: <input type="text" name="y2"><br>
<input type="button" onclick="myDrawing(x1,y1,x2,y2)" value="Draw Line">
<input type="button" onclick="saveImage()" value="Save Image">
</form>
</body>
</html>
Comments
You can follow this conversation by subscribing to the comment feed for this post.