I am trying to draw a shape on an HTML5 canvas but have the shape appear in a div (that can be manipulated by javascript). How can i do this? I would post code but i dont even know where to start with this. Please help.
To clarify: i want the shapes rendered on the canvas to be placed in divs. Sorry for any confusion.
Mozilla Drawing: https://developer.mozilla.org/en/Canvas_tutorial/Drawing_shapes
<div>
<canvas id="my_canvas"></canvas>
</div>
<script>
var canvas = document.getElementById('my_canvas');
// Set width height. You should probably use the width/height of the div.
canvas.width = 300;
canvas.height = 300;
var ctx = canvas.getContext('2d');
// Draw something with ctx.....
// ....
</script>
You could use the library Canvas2Image. It will allow you to convert what's on the Canvas into an image. There are some quirks on a per browser basis, but it is the closest thing to what you want to do without having to put many canvas elements on your page that you update in tandem.
Related
I'm drawing a image to a canvas, and when doing so the image gets downscaled to the canvas(which makes it lose quality) even though the image is the same size as the canvas, thats because the img does a good job scaling down the actual img that in reality has a bigger naturalheight and naturalwidth. I know there is possible ways to make this quality better, however i have no need of actually showing this canvas to the user/no need of downscaling. Therefore am i wondering if there is any way to drawImage that is bigger than the screen and hold it somewhere? Heard someone mention a box object or a camera object somewhere but couldn't really get use of that information only.
Question, is it possible to draw a canvas bigger than the screen? in that case how?
This is the code im working with atm
var image = document.getElementById('insertedImg');
var height = $("#insertedImg").height();
var width = $("#insertedImg").width();
var c=document.getElementById("canvass");
var ctx=c.getContext("2d");
c.height=height;
c.width=width;
ctx.drawImage(image,0,0,width,height);
Use an offscreen canvas, you just need to create a new canvas and set its height and width accordingly. Then you can append it to an element or export the image as a base64 string or whatever you need.
//canvas is not visible unless appended to a DOM element
var canvas = document.createElement('canvas');
canvas.width = $("#insertedImg").height();
canvas.height = $("#insertedImg").width();
var ctx = canvas.getContext('2d');
//do the drawing, etc.
ctx.drawImage(...);
//export the image
var img = canvas.toDataURL("image/png");
I want to use HTML5 canvas with flexbox. I need to set canvas.width and canvas.height automatically when user resizes window. I have tried to use jQuery for it:
$(".cnvs").attr("width", $(".cnvs").width());
$(".cnvs").attr("height", $(".cnvs").height());
but it keeps increasing actual width of canvas so it almost fills entire screen. I have put it on jsfiddle - try to resize output window with separator.
Is there any reasonable way how to do it? Thanks.
Edit: Just to be clear: I don't want to fill entire screen with that canvas. I want UI where I have:
<div class="container">
<div class="control"></div>
<canvas></canvas>
<div class="control"></div>
</div>
then use flexbox to put those three elements beside eachother, while canvas will be twice as wide as the other. This works without problem, but canvas.width and canvas.height doesn't get updated, so whenever I render something onto that canvas, it is rendered as if that canvas was 320x140 px.
Edit 2: I am sorry, but (perhaps because of my poor English) I am not clear enough. I will try to explain it once again:
Actual width of canvas element is correct (even without using any JavaScript code) only by using flexbox. My problem is that although width is correct (and $(".cnvs").width() returns correct value of width), it doesn't have any "width" attribute, it is still:
<canvas>
</canvas>
and I need to provide width argument by myself (because it renders badly when it's not set). When I try to use my code or proposed:
...
var rect = canvas.parentNode.getBoundingClientRect();
canvas.width = rect.width;
canvas.height = rect.height;
...
it behaves weirdly, canvas's width keeps increasing with every resize, but too much (it erases both control divs almost immediately).
Update 2
If I understand the question correct: the canvas has a flex CSS set (not shown in the question right now). It defines the canvas to be 2x the size of the other two elements, but since the canvas is resized and not its bitmap, the drawings are stretches as well and you want the bitmap to adopt dynamically.
If so, do this change to the code -
This update will leave the CSS rules of the canvas element alone and let flexbox handle it. It will read the actual pixel size of the element and then apply it to the bitmap so that data isn't stretched:
$(window).on("resize", function() {
var cnvs = $(".cnvs")[0]; // cache canvas element
var rect = cnvs.getBoundingClientRect(); // actual size of canvas el. itself
cnvs.width = rect.width;
cnvs.height = rect.height;
// ... redraw content here ...
}
Additionally, since resizing the window can produce a lot of events, you may want to consider "debouncing" so that you only deal with the more recent resize:
var timerID;
$(window).on("resize", function() {
clearTimeout(timerID);
timerID = setTimeout(function() {
var cnvs = $(".cnvs")[0]; // cache canvas element
var rect = cnvs.getBoundingClientRect(); // actual size of canvas el. itself
cnvs.width = rect.width;
cnvs.height = rect.height;
// ... redraw content here ...
}, 180); // adjust at will
}
This will delay the resizing/redrawing until 180ms has passed.
You don't even have to load jQuery, it is simple:
var canvas = document.querySelector("canvas");
window.addEventListener("resize", function(){
canvas.setAttribute("width", window.innerWidth);
canvas.setAttribute("height", window.innerHeight)
})
You have to add a listener to the resize event on the window object.
If your looking for a jquery solution.
$( window ).resize(function() {
$(".cnvs").attr("width", $(window).width());
$(".cnvs").attr("height", $(window).height());
});
This should work just fine.
I'm having a bit of trouble here to develop this functionality since it must work on IE9+ so css clip-path is not an option ( http://caniuse.com/#feat=css-clip-path ).
The issue:
I need to create a grid composed of 6 elements.
Each element is an image.
The images can be different according to user answers before getting to the grid page.
Eeach element / image must be clicable and will acquire a "selected" class that will overlay div with text and background image.
image:
What is the best way to achieve this?
One way to do this could be to save out each combination of the six images you require into one big image. Then, depending on the user's answer combination, you insert the corresponding image as a background-image of a div. You then overlay click-able hotspots within the same div that roughly correlate to the dividing edges.
This may however not be the most practical solution and largely depends on how many answers/images you are dealing with.
Alternatively you could draw SVG shapes and set their fills to the images you require.
I can recommend Raphael.js as a starting point. You should be able to find what you need in the documentation
Another option would be to use HTML5 canvas:
http://jsfiddle.net/julienbidoret/GKP7X/1/
(credit goes to julienbidoret for the jsfiddle)
Javascript:
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');
img.onload = function () {
ctx.save();
ctx.beginPath();
ctx.moveTo(20, 0);
ctx.lineTo(240, 0);
ctx.lineTo(220, 240);
ctx.lineTo(0, 240);
ctx.closePath();
ctx.clip();
ctx.drawImage(img, 0, 0);
ctx.restore();
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/2/2b/Clouds.JPG";
HTML:
<canvas id="c" width="300" height="300" ></canvas>
Both SVG and canvas are supported in IE9.
How can I achieve, so that the HTML5 canvas element ist resizeable?
I would like to implement this element so that you can scale it in any size. The event of the scaling should be the mouse which snaps the edge and the user resizes the element.
I've already read about how you can achieve this on a object in the canvas element. But in my case I need this on the canvas element itself (<canvas>).
Setting a canvas's width or height properties has the effect of clearing the canvas. Even canvas.width = canvas.width; will cause you to lose everything in the canvas. Sometimes this is desirable, but in your case it probably isn't.
What you will probably need to do is something like this
var myCanvas = document.getElementById('myCanvas');
var tempCanvas = document.createElement('canvas');
tempCanvas.width = myCanvas.width;
tempCanvas.height = myCanvas.height;
// save your canvas into temp canvas
tempCanvas.getContext('2d').drawImage(myCanvas, 0, 0);
// resize my canvas as needed, probably in response to mouse events
myCanvas.width = newWidth;
myCanvas.height = newHeight;
// draw temp canvas back into myCanvas, scaled as needed
myCanvas.getContext('2d').drawImage(tempCanvas, 0, 0, tempCanvas.width, tempCanvas.height, 0, 0, myCanvas.width, myCanvas.height);
In most browsers, the scaling will be done with a bicubic scaling algorithm, causing it to get blurry. In some cases you can set a CSS property to cause nearest neighbor on the canvas if you want, but browser support for this is very spotty right now. You can instead manually do a nearest neighbor scale , as this question shows: How to stretch images with no antialiasing
Alternative CSS Approach
Another approach is to scale the canvas using CSS. In Chrome/Safari/IE you can just do:
<canvas style="zoom:200%" />
In Firefox, you can use a scale transform to achieve the same effect:
<canvas style="-moz-transform:scale(2)" />
In many ways this approach is easier, but it comes with its own little gotchas and browser specific quirks.
I think you need to bind the onresize event to your body of document.
Then inside the the event you need to resize the canvas using window.innerWidth and window.innerHeight.
Have a look # http://kile.stravaganza.org/lab/js/canvas_resize/ (view source)
Although it's a bit late to answer this question, I'd like to share what I found to solve the same question. Take it a look please.
panel.css
#Panel {
width: 100%;
height: 30%;
}
app.js
var widthG = 0, height=G = 0;
function updateScale() {
widthG = parseInt($('#Panel').width());
heightG = parseInt($('#anel').height());
}
...
function updateCanvas() {
ctx = $('#canvas').get(0).getContext('2d');
ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
ctx.canvas.width = widthG;
ctx.canvas.width = heightG;
}
I also tried to re-assign these properties by css syntax, but it doesn't work.
$('#canvas').width(panelW);
$('#canvas').height(panelH);
Hope this helps ppl suffered from the same question.
I'm creating a HTML Canvas object using this javascript code:
var Canvas = document.createElement("canvas");
Canvas.style.width = "500px";
and then i'm drawing text upon it.
When the canvas is displayed, the whole canvas has been scaled up (including content) to to match the 500px width, which results in ugly resampling. What i really want, is that the content stay the same size, only the canvas itself made bigger.
Any ideas?
Try changing the element’s width instead of its CSS width.
Canvas.width = 500;
Thomas' answer is correct, but it sound's like you also want to keep the existing content on the canvas. When you change the canvas size, it automatically gets cleared and reset to it's default state. Because of that, you will either need to redraw the contents, or copy the contents to another canvase (using drawImage), resize the canvas, then copy the contents back (again, using drawImage).