How to resize html canvas element? - javascript

I have a canvas element defined statically in the html with a width and height. If I attempt to use JavaScript to resize it dynamically (setting a new width and height - either on the attributes of the canvas or via the style properties) I get the following error in Firefox:
uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame :: file:///home/russh/Desktop/test.html :: onclick :: line 1" data: no]
Is it possible to resize this element or do I have to destroy it and create a new element on the fly?

You didn't publish your code, and I suspect you do something wrong. it is possible to change the size by assigning width and height attributes using numbers:
canvasNode.width = 200; // in pixels
canvasNode.height = 100; // in pixels
At least it works for me. Make sure you don't assign strings (e.g., "2cm", "3in", or "2.5px"), and don't mess with styles.
Actually this is a publicly available knowledge — you can read all about it in the HTML canvas spec — it is very small and unusually informative. This is the whole DOM interface:
interface HTMLCanvasElement : HTMLElement {
attribute unsigned long width;
attribute unsigned long height;
DOMString toDataURL();
DOMString toDataURL(in DOMString type, [Variadic] in any args);
DOMObject getContext(in DOMString contextId);
};
As you can see it defines 2 attributes width and height, and both of them are unsigned long.

Note that if your canvas is statically declared you should use the width and height attributes, not the style, eg. this will work:
<canvas id="c" height="100" width="100" style="border:1px"></canvas>
<script>
document.getElementById('c').width = 200;
</script>
But this will not work:
<canvas id="c" style="width: 100px; height: 100px; border:1px"></canvas>
<script>
document.getElementById('c').width = 200;
</script>

I just had the same problem as you, but found out about the toDataURL method, which proved useful.
The gist of it is to turn your current canvas into a dataURL, change your canvas size, and then draw what you had back into your canvas from the dataURL you saved.
So here's my code:
var oldCanvas = canvas.toDataURL("image/png");
var img = new Image();
img.src = oldCanvas;
img.onload = function (){
canvas.height += 100;
ctx.drawImage(img, 0, 0);
}

<div id="canvasdiv" style="margin: 5px; height: 100%; width: 100%;">
<canvas id="mycanvas" style="border: 1px solid red;"></canvas>
</div>
<script>
$(function(){
InitContext();
});
function InitContext()
{
var $canvasDiv = $('#canvasdiv');
var canvas = document.getElementById("mycanvas");
canvas.height = $canvasDiv.innerHeight();
canvas.width = $canvasDiv.innerWidth();
}
</script>

This worked for me just now:
<canvas id="c" height="100" width="100" style="border:1px solid red"></canvas>
<script>
var c = document.getElementById('c');
alert(c.height + ' ' + c.width);
c.height = 200;
c.width = 200;
alert(c.height + ' ' + c.width);
</script>

Here's my effort to give a more complete answer (building on #john's answer).
The initial issue I encountered was changing the width and height of a canvas node (using styles), resulted in the contents just being "zoomed" or "shrunk." This was not the desired effect.
So, say you want to draw two rectangles of arbitrary size in a canvas that is 100px by 100px.
<canvas width="100" height="100"></canvas>
To ensure that the rectangles will not exceed the size of the canvas and therefore not be visible, you need to ensure that the canvas is big enough.
var $canvas = $('canvas'),
oldCanvas,
context = $canvas[0].getContext('2d');
function drawRects(x, y, width, height)
{
if (($canvas.width() < x+width) || $canvas.height() < y+height)
{
oldCanvas = $canvas[0].toDataURL("image/png")
$canvas[0].width = x+width;
$canvas[0].height = y+height;
var img = new Image();
img.src = oldCanvas;
img.onload = function (){
context.drawImage(img, 0, 0);
};
}
context.strokeRect(x, y, width, height);
}
drawRects(5,5, 10, 10);
drawRects(15,15, 20, 20);
drawRects(35,35, 40, 40);
drawRects(75, 75, 80, 80);
Finally, here's the jsfiddle for this: http://jsfiddle.net/Rka6D/4/ .

Prototypes can be a hassle to work with, and from the _PROTO part of the error it appears your error is caused by, say, HTMLCanvasElement.prototype.width, possibly as an attempt to resize all the canvases at once.
As a suggestion, if you are trying to resize a number of canvases at once, you could try:
<canvas></canvas>
<canvas></canvas>
<canvas></canvas>
<script type="text/javascript">
...
</script>
In the JavaScript, instead of invoking a prototype, try this:
$$ = function(){
return document.querySelectorAll.apply(document,arguments);
}
for(var i in $$('canvas')){
canvas = $$('canvas')[i];
canvas.width = canvas.width+100;
canvas.height = canvas.height+100;
}
This would resize all the canvases by adding 100 px to their size, as is demonstrated in this example
Hope this helped.

Related

Canvas height and width

When programming in HTML canvas, the js dimensions of the canvas don't always match the css dimensions.
Why is this happening and how can I fix this?
I've found the problem. I was setting the dimensions of the  using CSS, when you actually have to set the width and height attributes. This was causing it to be stretched/skewed.
var canvas = $('<canvas/>').attr({width: cw, height: ch}).appendTo('body');
http://jsfiddle.net/h2yJn/66/
You can try to set the width and height of the canvas to be equal to the dimensions of the window object:
function createCanvas() {
var ctx = //the canvas context;
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
//your code
}
In addition, it is a good idea to set the body and html tags to the full width of the window:
body, html{
height: 100%;
width: 100%;
}
You can also do this by using pure javascript and set the dimensions of the canvas in javascript depending on your CSS values:
//Get Canvas
var canvas = document.getElementById("canv");
// Get computed style of the canvas element.
var cstyle = window.getComputedStyle(canvas);
// Returns the width as str in px: e.g. 600px.
// Parse resolves that issue.
canv.width = parseInt(cstyle.width);
canv.height = parseInt(cstyle.height);
Demo:
https://jsfiddle.net/ofaghxfq/2/

How to convert canvas image to standard img? [duplicate]

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....

Is there any way to make an html5 canvas element resizeable?

Is there a native solution that provides a handle in the corner of my HTML5 canvas similar to that in a default <textarea> element.
<textarea>resizeable</textarea>
I assume this will clear the canvas and will require a redraw as this is the case when resizing the canvas programmatically with canvas.width and canvas.height.
I looked around and found nothing, but wanted to check before rolling my own. If anyone is sure that there is no "easy" way, then that is a perfectly acceptable answer. Thanks!
The best I could come up with was use jQueryUI Resizable like so
jsFiddle : https://jsfiddle.net/n24dbaw9/
Html
<div class="resizable">
<canvas id="myCanvas"></canvas>
</div>
CSS
.resizable{
width: 400px;
height: 400px;
}
#myCanvas{
width: 100%;
height: 100%;
}
Javascript
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#777";
$(function() {
$(".resizable").resizable();
});
setInterval(function(){ ctx.fillRect(0, 0, 400, 400); }, 3);
Basically I have styled the canvas to fit inside of the "resizble" div, which is set to 400 by 400 at default. The canvas has a style which is 100% width and height so when the user resizes the "resizble" div the canvas will then just stretch out.
You will want to put the canvas into a JavaScript draw() function:
function draw() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
}
and your body element in css should have height and width set to 100%

Cannot save canvas with draggable object

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.

Can I get image from canvas element and use it in img src tag?

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....

Categories

Resources