I wanted to know if it is possible to create an image using html5. Currently i am creating a text using canvas, now i want to convert that text into an image.
2 Answers
In order to save the canvas to an image file, you can use Nihilogic's code.
Use the canvas text functions.
For example:
<html>
<head>
<title>Canvas tutorial</title>
<script type="text/javascript">
function draw(){
var canvas = document.getElementById('tutorial');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
ctx.fillText("Sample String", 10, 50);
}
}
</script>
<style type="text/css">
canvas { border: 1px solid black; }
</style>
</head>
<body onload="draw();">
<canvas id="tutorial" width="150" height="150"></canvas>
</body>
</html>
6 Comments
user475685
If i am not wrong, the link specifies how to draw text in canvas. I want to create an image.
Chi-Lan
Oh, sorry. What do you mean "create an image"? Enable the user to save the image on his hard drive? Look at my updated answer, is that what you meant?
Chi-Lan
I don't understand, the user already sees that as if it was an image. What additional option you want the user to have, that makes it "as if it was an image?"
user475685
i just want to know if it is possible.
Chi-Lan
Chi-Lan, again, I don't understand what you're trying to do, so I can't really tell if it's possible or not.
|
Create an image DOM element, and set the src to the canvas.toDataURL method.
var c = document.getElementById("c");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 50, 50);
function copy() {
var image = document.getElementById("Img");
image.src = c.toDataURL("image/png");
}
<canvas id="c" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<img id="Img" width="300" height="150" style="border:1px solid #d3d3d3;"/>
<button onclick="copy()">Copy</button>