Would like to ask if there's a way for transferring <canvas> contents to another <div>. So that after putting the signature, it will be previewed on the inside of the <div> it was transferred to.
I've used this library https://github.com/szimek/signature_pad on our previous project and the signature looks real, like it was written by a pen.
This library can save the signature to a file, so what I did on our previous project is once I submit the form, the signature will be saved and it will be previewed by attaching the source file to an <img> element.
What I would like to do is I have a <button> that will show a modal that contains a signature pad and once the modal is closed, the signature will be transferred to another <div> wherein its size will shrink depending on the div's size without having to save the signature on a file.
Thanks.
Take a look at HTMLCanvasElement.toDataURL. This will give you an image of the canvas as a Data URI, which you can then add to your page as an image.
Here's a simple example:
let canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d');
// Draw something
ctx.fillStyle = "lightgray";
ctx.fillRect(0, 0, 200, 100);
ctx.fillStyle = 'orange';
ctx.fillRect(20, 20, 160, 60);
ctx.fillStyle = 'black';
ctx.font = "50px monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("image", 100, 50);
// Make the image and put it in the output
let uri = canvas.toDataURL('image/png'),
outdiv = document.querySelector('#out'),
outimg = new Image();
outimg.src = uri;
outdiv.appendChild(outimg);
<div style="display: inline-block;">
<h6>Canvas with border</h6>
<canvas width="200" height="100"
style="border: 1px solid black;">
</canvas>
</div>
<div style="display: inline-block;">
<h6>Output image in a <code>div</code></h6>
<div id="out"></div>
</div>
Related
The program includes a rectangle with a given color based on a button clicked in the HTML passing the color into the method. There is also another text field and button to add text to this rectangle but the color of the text isn't staying independent from the rectangle color. This means the rectangle always gets set to whatever color the text is. What I am trying to do is have the color of the bag selectable and then have the text on the bag selectable whilst keeping the color of the bag the same. I thought the context.beginPath() is supposed to allow these to be seperate but it doesnt seem to be doing that. Any help on what I should be doing instead?
JavaScript File
function drawCanvas(color) {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var logoText = document.getElementById("logoText").value;
//Draws the bag and sets the color
context.beginPath()
context.fillStyle = color;
context.fillRect(10,30,200,200);
//Draws the border outline of the bag
context.beginPath();
context.lineWidth = "2";
context.rect(10,30,200,200);
context.stroke()
//Draws the handle
context.beginPath();
context.lineWidth = "2";
context.rect(85,5,50,25);
context.stroke();
context.save();
context.restore();
context.beginPath();
context.font = "24px Times";
context.fillStyle = "black";
context.textAlign = "center";
context.fillText(logoText, canvas.width/2, canvas.width/2);
}
window.onload = drawCanvas;
HTML File
<!DOCTYPE html>
<html lang = "en">
<head>
<title>mas00266 - Plastic Bag Inc. - Order Page</title>
<link rel = "stylesheet" href = "stylesheet.css" />
<script type = "text/javascript" src = "script.js"></script>
<meta charset = "UTF-8">
</head>
<body>
<div class = "flex-container">
<div class = "box">
<h1 id = "left"> The Bag Company </h1>
</div>
<div class = "box">
<h3 style = "text-align: right; padding: 15px"> Welcome to our orders page! </h3>
</div>
</div>
<nav>
<ul class = "navStyle">
<li>Home</li>
<li class = "active">Order</li>
<li>Contact</li>
<li>Login</li>
</ul>
</nav>
<br>
<br>
<canvas id = "myCanvas" width = "220" height = "240"></canvas>
<br>
<br>
<h4>Choose your bag color:</h4>
<button type = "button" onclick = "drawCanvas('black')">Black</button>
<button type = "button" onclick = "drawCanvas('white')">White</button>
<button type = "button" onclick = "drawCanvas('red')">Red</button>
<button type = "button" onclick = "drawCanvas('blue')">Blue</button>
<button type = "button" onclick = "drawCanvas('green')">Green</button>
<br>
<h4>Enter text on the bag:</h4>
<input id = "logoText" type = "text" name = "textInputField" size = "12">
<button type = "button" onclick = "drawCanvas()">Add Text</button>
</body>
</html>
MDN has this to say on .beginPath(), .save(), and .restore():
The CanvasRenderingContext2D.beginPath() method of the Canvas 2D API starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.
The CanvasRenderingContext2D.save() method of the Canvas 2D API saves the entire state of the canvas by pushing the current state onto a stack.
The CanvasRenderingContext2D.restore() method of the Canvas 2D API restores the most recently saved canvas state by popping the top entry in the drawing state stack. If there is no saved state, this method does nothing.
As you can see, .beginPath() doesn't have anything to do with drawing context other than setting up for a new path. Instead, you would use .save() to create a kind of save point for the current context (which includes all the current drawing parameters such colors, patterns, and transforms), make and use your changes to that context, then use .restore() to recover from those changes by reverting to the previous save point.
Based on that, and your goal, your code should look something like:
function drawCanvas(color) {
// onload doesn't call this with an argument so make sure we have a default
color = color || "blue";
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var logoText = document.getElementById("logoText").value;
//Set various base styles in our drawing context
context.fillStyle = "black";
context.font = "24px Times";
context.textAlign = "center";
context.lineWidth = "2";
//Draws the bag and sets the color
context.save(); // save current drawing context state to the stack
context.fillStyle = color;
context.fillRect(10,30,200,200);
content.restore(); // recover to previous saved state and remove it from the stack
//Draws the border outline of the bag
context.rect(10,30,200,200);
context.stroke()
//Draws the handle
context.rect(85,5,50,25);
context.stroke();
context.fillText(logoText, canvas.width/2, canvas.width/2);
}
window.onload = drawCanvas;
Is there possibility to convert the image present in a canvas element into an image representing by img src?
I need that to crop an image after some transformation and save it. There are a view functions that I found on the internet like: FileReader() or ToBlop(), toDataURL(), getImageData(), but I have no idea how to implement and use them properly in JavaScript.
This is my html:
<img src="http://picture.jpg" id="picture" style="display:none"/>
<tr>
<td>
<canvas id="transform_image"></canvas>
</td>
</tr>
<tr>
<td>
<div id="image_for_crop">image from canvas</div>
</td>
</tr>
In JavaScript it should look something like this:
$(document).ready(function() {
img = document.getElementById('picture');
canvas = document.getElementById('transform_image');
if(!canvas || !canvas.getContext){
canvas.parentNode.removeChild(canvas);
} else {
img.style.position = 'absolute';
}
transformImg(90);
ShowImg(imgFile);
}
function transformImg(degree) {
if (document.getElementById('transform_image')) {
var Context = canvas.getContext('2d');
var cx = 0, cy = 0;
var picture = $('#picture');
var displayedImg = {
width: picture.width(),
height: picture.height()
};
var cw = displayedImg.width, ch = displayedImg.height
Context.rotate(degree * Math.PI / 180);
Context.drawImage(img, cx, cy, cw, ch);
}
}
function showImg(imgFile) {
if (!imgFile.type.match(/image.*/))
return;
var img = document.createElement("img"); // creat img object
img.id = "pic"; //I need set some id
img.src = imgFile; // my picture representing by src
document.getElementById('image_for_crop').appendChild(img); //my image for crop
}
How can I change the canvas element into an img src image in this script? (There may be some bugs in this script.)
canvas.toDataURL() will provide you a data url which can be used as source:
var image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
document.getElementById('image_for_crop').appendChild(image);
Complete example
Here's a complete example with some random lines. The black-bordered image is generated on a <canvas>, whereas the blue-bordered image is a copy in a <img>, filled with the <canvas>'s data url.
// This is just image generation, skip to DATAURL: below
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d");
// Just some example drawings
var gradient = ctx.createLinearGradient(0, 0, 200, 100);
gradient.addColorStop("0", "#ff0000");
gradient.addColorStop("0.5" ,"#00a0ff");
gradient.addColorStop("1.0", "#f0bf00");
ctx.beginPath();
ctx.moveTo(0, 0);
for (let i = 0; i < 30; ++i) {
ctx.lineTo(Math.random() * 200, Math.random() * 100);
}
ctx.strokeStyle = gradient;
ctx.stroke();
// DATAURL: Actual image generation via data url
var target = new Image();
target.src = canvas.toDataURL();
document.getElementById('result').appendChild(target);
canvas { border: 1px solid black; }
img { border: 1px solid blue; }
body { display: flex; }
div + div {margin-left: 1ex; }
<div>
<p>Original:</p>
<canvas id="canvas" width=200 height=100></canvas>
</div>
<div id="result">
<p>Result via <img>:</p>
</div>
See also:
MDN: canvas.toDataURL() documentation
Do this. Add this to the bottom of your doc just before you close the body tag.
<script>
function canvasToImg() {
var canvas = document.getElementById("yourCanvasID");
var ctx=canvas.getContext("2d");
//draw a red box
ctx.fillStyle="#FF0000";
ctx.fillRect(10,10,30,30);
var url = canvas.toDataURL();
var newImg = document.createElement("img"); // create img tag
newImg.src = url;
document.body.appendChild(newImg); // add to end of your document
}
canvasToImg(); //execute the function
</script>
Of course somewhere in your doc you need the canvas tag that it will grab.
<canvas id="yourCanvasID" />
I´ve found two problems with your Fiddle, one of the problems is first in Zeta´s answer.
the method is not toDataUrl(); is toDataURL(); and you forgot to store the canvas in your variable.
So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/
I hope this helps!
canvas.toDataURL is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.
Corrected the Fiddle - updated shows the Image duplicated into the Canvas...
And right click can be saved as a .PNG
http://jsfiddle.net/gfyWK/67/
<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>
Plus the JS on the fiddle page...
Cheers
Si
Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....
I have a textarea and canvas. The user is able to drag image onto the canvas and change different background images. Now I need to be able to have a section at the bottom of canvas that will display text from textarea.
<canvas id="canvas" width="640" height="280"></canvas>
<div id="text">
<textarea id="write_whatever">Write 4 lines to describe yourself.</textarea>
<div id="button_to_add"></div>
</div>
Here's the jsfiddle of what i currently have http://jsfiddle.net/D4zw4/50/
Here's what I am trying to achieve, but instead of key up it's with button click and it should be at the bottom of the canvas http://jsfiddle.net/m1erickson/NuaHp/
Anyone know how I could achieve this or done this before? Thanks in advance :)
Something like this?
$('#button_to_add').on('click', 'button', function () {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var text = $('#write_whatever').val();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#3e3e3e";
ctx.font = "16px Arial";
ctx.fillText(text, 20, canvas.height - 20);
});
http://jsfiddle.net/D4zw4/51/
I'm trying to save my HTML canvas to file which I can successfully do, but it's not saving any objects I've dragged into the canvas.
So, by using the Draggable JQuery I can happily move my object around screen and place it ontop of my canvas. When I save the canvas using the Canvas.ToDataURL() it does not save my dragged objects (and also does something strange to my canvas in the jsFiddle, it appears to change the colour of my canvas?).
To see a "working" example, please visit my jsFiddle http://jsfiddle.net/JVSFS/74/
Please simply drag the green box over the blue box and click the save button. The result will be shown underneath (just an orange box).
HTML
<canvas id="MyCanvas" class="canvas"></canvas>
<div class="popup_click">
<div id="popup_title">Drag</div>
</div>
<asp:HiddenField ID="hideMe" runat="server" />
<asp:Button runat="server" OnClick="ClickMe" Text="Click" OnClientClick="SaveMe()" />
<button onclick="SaveMe()">Try it</button>
<p>Results: </p>
<img id="myImage" />
JavaScript
$(document).ready(function () {
$('.popup_click').show(0).draggable();
});
function SaveMe() {
var canvas = document.getElementById("MyCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "orange";
context.fillRect(0, 0, 100, 100);
var image = canvas.toDataURL("image/png");
document.getElementById("myImage").src = image;
document.getElementById("hideMe").value = image;
}
CSS
.popup_click {
background: #80FF80;
width: 50px; }
.canvas {
width: 100px;
height: 100px;
background-color: #0FC;
}
How can I get the dragged object to save? I assume I have to tell the Canvas that the object is part of it's context but no idea how and my own searches came up with nothing.
From https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas
You can't just draw HTML into a canvas. Instead, you need to use an SVG image containing the content you want to render. To draw HTML content, you'd use a element containing the HTML, then draw that SVG image into your canvas.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var data = "<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
"<foreignObject width='100%' height='100%'>" +
"<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>" +
"<em>I</em> like <span style='color:white; text-shadow:0 0 2px blue;'>cheese</span>" +
"</div>" +
"</foreignObject>" +
"</svg>";
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
};
img.src = url;
That's because your draggable object isn't in the canves.
They are simple html elements.
It'll save only the objects whose created with canvas methods.
Any way to create html elements on canvas you have to use svg.
Mozilla show nice way to to this but you need to get all the css to inline css before.
mozilla explanation
Anyway with using svg on you canvas you won't be able to use toDataUrl because of security policy.
Is there possibility to convert the image present in a canvas element into an image representing by img src?
I need that to crop an image after some transformation and save it. There are a view functions that I found on the internet like: FileReader() or ToBlop(), toDataURL(), getImageData(), but I have no idea how to implement and use them properly in JavaScript.
This is my html:
<img src="http://picture.jpg" id="picture" style="display:none"/>
<tr>
<td>
<canvas id="transform_image"></canvas>
</td>
</tr>
<tr>
<td>
<div id="image_for_crop">image from canvas</div>
</td>
</tr>
In JavaScript it should look something like this:
$(document).ready(function() {
img = document.getElementById('picture');
canvas = document.getElementById('transform_image');
if(!canvas || !canvas.getContext){
canvas.parentNode.removeChild(canvas);
} else {
img.style.position = 'absolute';
}
transformImg(90);
ShowImg(imgFile);
}
function transformImg(degree) {
if (document.getElementById('transform_image')) {
var Context = canvas.getContext('2d');
var cx = 0, cy = 0;
var picture = $('#picture');
var displayedImg = {
width: picture.width(),
height: picture.height()
};
var cw = displayedImg.width, ch = displayedImg.height
Context.rotate(degree * Math.PI / 180);
Context.drawImage(img, cx, cy, cw, ch);
}
}
function showImg(imgFile) {
if (!imgFile.type.match(/image.*/))
return;
var img = document.createElement("img"); // creat img object
img.id = "pic"; //I need set some id
img.src = imgFile; // my picture representing by src
document.getElementById('image_for_crop').appendChild(img); //my image for crop
}
How can I change the canvas element into an img src image in this script? (There may be some bugs in this script.)
canvas.toDataURL() will provide you a data url which can be used as source:
var image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
document.getElementById('image_for_crop').appendChild(image);
Complete example
Here's a complete example with some random lines. The black-bordered image is generated on a <canvas>, whereas the blue-bordered image is a copy in a <img>, filled with the <canvas>'s data url.
// This is just image generation, skip to DATAURL: below
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d");
// Just some example drawings
var gradient = ctx.createLinearGradient(0, 0, 200, 100);
gradient.addColorStop("0", "#ff0000");
gradient.addColorStop("0.5" ,"#00a0ff");
gradient.addColorStop("1.0", "#f0bf00");
ctx.beginPath();
ctx.moveTo(0, 0);
for (let i = 0; i < 30; ++i) {
ctx.lineTo(Math.random() * 200, Math.random() * 100);
}
ctx.strokeStyle = gradient;
ctx.stroke();
// DATAURL: Actual image generation via data url
var target = new Image();
target.src = canvas.toDataURL();
document.getElementById('result').appendChild(target);
canvas { border: 1px solid black; }
img { border: 1px solid blue; }
body { display: flex; }
div + div {margin-left: 1ex; }
<div>
<p>Original:</p>
<canvas id="canvas" width=200 height=100></canvas>
</div>
<div id="result">
<p>Result via <img>:</p>
</div>
See also:
MDN: canvas.toDataURL() documentation
Do this. Add this to the bottom of your doc just before you close the body tag.
<script>
function canvasToImg() {
var canvas = document.getElementById("yourCanvasID");
var ctx=canvas.getContext("2d");
//draw a red box
ctx.fillStyle="#FF0000";
ctx.fillRect(10,10,30,30);
var url = canvas.toDataURL();
var newImg = document.createElement("img"); // create img tag
newImg.src = url;
document.body.appendChild(newImg); // add to end of your document
}
canvasToImg(); //execute the function
</script>
Of course somewhere in your doc you need the canvas tag that it will grab.
<canvas id="yourCanvasID" />
I´ve found two problems with your Fiddle, one of the problems is first in Zeta´s answer.
the method is not toDataUrl(); is toDataURL(); and you forgot to store the canvas in your variable.
So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/
I hope this helps!
canvas.toDataURL is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.
Corrected the Fiddle - updated shows the Image duplicated into the Canvas...
And right click can be saved as a .PNG
http://jsfiddle.net/gfyWK/67/
<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>
Plus the JS on the fiddle page...
Cheers
Si
Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....