Im currently doing something that goes like:
create a canvas and append it to a divider
set a background image via CSS on that canvas.
draw a hexgrid on the canvas
draw PNGs on the canvas.
animate those PNGs to display "movement".
However, its a pain having to redraw the entire canvas including the non-moving PNGs.
Im wondering if it would be smarter or better to have a single canvas for the Background/hexgrid and create the PNGs on additional, small canvas elements which are then zIndex'ed on top of the Background canvas. I then could make the animations (PNGs moving) easier.
However, im running into problems in regards to actually placing the "new" canvas's at the right x/y coordinates of the Background canvas.
this.drawShipImage = function(name, id, x, y){
var div = document.getElementById("grid");
// initial, big canvas with background is created elsewhere but has the same width/height than "grid"
var canvas = document.createElement("canvas");
canvas.id = name + id;
canvas.width = 30;
canvas.height = 30;
canvas.style.position = "absolute";
canvas.style.zIndex = 1;
var context = canvas.getContext("2d");
context.scale(0.75, 0.75);
context.drawImage(ship, 0, 0);
div.appendChild(canvas);
}
Basicly, this function has 2 important Parameters, that is the x/y Parameter where the new canvas SHOULD be drawn in context to the width/height of the Background canvas.
However im unable to conclude a way to get the Image to appear at the right coordinates.
I suppose the only way it could work is adding
canvas.style.margin = x/y-ish
into the mix ?
Using a second canvas (or just an img element holding your background) might be a good solution since your background will be redrawn less frequently than your animated foreground.
This is particularly true if your device has a GPU because the background element will be cached in the GPU and will redraw very quickly as compared with the relatively slower drawings on your animating foreground canvas.
You can use the CSS position property to stack 2 elements.
Wrap your 2 canvases (or canvas + img elements) in a wrapping div.
Set the wrapper div's position property to relative (meaning children will be positioned relative to the wrapper instead of relative to the page).
Set the 2 canvases (or canvas + img elements) position to 'absolute' (meaning they are subject to being positioned relative to the wrapper).
Set the top & left properties of the child elements to 0 so they will overlap. The default top & left values are zero, so assigning them to zero is optional--but explicitly assigning them to zero is more clear.
HTML
<div id='wrapper'>
<canvas id="canvasBottom" width=300 height=200></canvas>
<canvas id="canvasTop" width=300 height=200></canvas>
</div>
CSS
#wrapper{
position:relative;
width:300px;
height:200px;
}
#canvasTop,#canvasBottom{
position:absolute; top:0px; left:0px;
border:1px solid green;
width:300px;
height:200px;
}
#canvasTop{
border:1px solid red;
}
Layer canvas elements via KineticJS
It's really easy to layer canvas elements via KineticJS from Eric Rowell. It's a very useful library to work with the HTML5 canvas element.
The lib is not maintained anymore but its very stable.
Get it here: KineticJS Download
Find the reference here: KineticJS Reference
If you search a little bit on the web for examples you will clearly understand that every node in KineticJS is an own canvas element. This library relies on layering canvas elements via groups and so on.
Related
I am playing around with a project to learn more about node.js & html canvases.
In my project I have a canvas that I want to keep a fixed bitmap size, but fill its containing div while maintaining its aspect ratio.
I have applied a size of 500x500 to my canvas element, and then applied the following style in CSS.
canvas {
display: block;
width:100%;
height:100%;
object-fit: contain;
background-color: lightgrey;
}
Inside the javascript initially fill the canvas white so I get something like the below, so far so good.
I hook into the mouse events and use them to draw lines. I use the below function to correctly scale events to the canvas.
function getMousePos(evt) {
var rect = canvas.getBoundingClientRect(); // abs. size of element
var raw_x = evt.clientX||evt.touches[0].clientX;
var raw_y = evt.clientY||evt.touches[0].clientY;
var min_dimension = Math.min(rect.width,rect.height);
var x_offset = 0.5*(rect.width-min_dimension);
var y_offset = 0.5*(rect.height-min_dimension);
return {
x: ((raw_x - rect.left - x_offset) / min_dimension) * canvas.width,
y: ((raw_y - rect.top - y_offset) / min_dimension) * canvas.height
}
}
This works, however when drawing on the canvas when the mouse moves over a band on the right side of the image it doesn't update until the mouse leaves the band. The band is the same size as the space on the left of the canvas so I think its related but I don't know how to investigate. I have no Issues if I resize the window till there is no space on either side of the canvas bitmap (and performance is considerably faster). The below gif should make things more clear.
Does anyone have a suggestion on what could be causing this, or a better way for me to achieve the same effect.
Note: I am running chrome version 80.0.3987.149
For anyone else that comes across this, I couldn't find a good solution, beyond using JavaScript to resize the element when the window resize event occurs.
I am drawing a series of rectangles and text on an HTML5 Canvas. But this canvas will ultimately be printed. The rectangles are drawn according of the height of the paper(canvas)
The only canvas width that doesn't distort the text is the 300dpi or 2400x3300 canvas. This works well for print but its obviously huge on the screen.
I would like the user to have a scaled down version of the canvas on the left side that fits 100% height of the parent container with scroll bars for overflow.
I have tried div overflow:auto.. and this does work but its not scaled (still scrolling a huge version). So basically I would like to scale the image for the browser window but do all drawing/printing from the big canvas.
For this scenario you can use CSS rules with the canvas.
ONLINE DEMO HERE
Keep the pixel size but add the following rules to the canvas element itself (assuming the id of the canvas is canvas):
canvas.style.width = 'auto';
canvas.style.height = '100%';
or apply a CSS rule to the element via CSS and HTML:
.printCanvas {
width:auto;
height:100%;
}
and then in the HTML:
<canvas id="canvas" class="printCanvas" width="2400" height="3300"></canvas>
This should allow the browser to use the actual content of the canvas when printing even when the canvas is scaled down (like with an image).
In this example the canvas will fit the height of parent provided the parent has height defined. You can use as you already do overflow:auto to get scroll-bars.
If you want to show 50% of the canvas inside the parent just set height:200% for the canvas element and so on.
Note that you might loose some details on the screen if the canvas is scaled much but these should show on the print. This would be due to sub-pixeling which kicks in when a pixel is drawn as less than an actual pixel on the screen.
I am using the visualisation arborjs and I am trying to implement the zoom-function. This isn't included in the visualisation itself so I had to try some different approches.
I can't use the html5 canvasfunction .scale because with this the positions given by the visualisation don't match the real positions anymore.
For the moment I just increase the height and width of the canvas to zoom in. This doesn't give any problems with the positioningproblem, but I can't scroll in the canvas.
The only problem that I have to solve is the scrollfunction to make this work. So my question is: can I add scrollbars to the canvas when the canvas becomes too big.
Initially the canvas has width 100% and height 100%, so no scrollbars are needed, but when I enlarge this I need those scrollbars.
I tried the css-style overflow:scroll for both the canvas and the surrounding div, but no results.
Here is the relevant code:
HTML:
<div class="explore_area">
<canvas class="explore_area" id="viewport">
</canvas>
</div>
javascript:
zoom: function(){
var canvas = document.getElementById("viewport");
var ctx = canvas.getContext('2d');
sys.screenSize((canvas.width*1.5), (canvas.height*1.5));
}
css:
div.explore_area {
position:relative;
width:100%;
height:600px;
overflow:hidden;
}
canvas.explore_area{
float:left;
height:550px;
width:100%;
}
Setting the width and height of canvas using css is not a good idea. To achieve what you required you should not give width and height of canvas in css. Even if you change the dimension css will reset it.
so first you need to give dimension like this
<canvas class="explore_area" id="viewport" width="400" height="300">
css for container
div.explore_area {
position:relative;
width:400px;
height:300px;
overflow:auto;
}
see the demo here : http://jsfiddle.net/diode/sHbKD/22/ ( not using arborjs)
I can't use the html5 canvasfunction .scale because with this the positions given by the visualisation don't match the real positions anymore.
What do you mean by that ?? If you want to draw an image same place, but zoomed, you can do :
ctx.save();
ctx.scale(ratio, ratio);
ctx.drawImage(myImage, x/ratio, y/ratio ) ;
ctx.restore();
Or if you want to zoom from the middle of the image :
ctx.save();
ctx.translate(x + myImage.width/2, y + myImage.height/2 );
ctx.scale(ratio, ratio);
ctx.drawImage(myImage, - myImage.width/(2*ratio), - myImage.width/(2*ratio) ) ;
ctx.restore();
Rq : For clarity, i did not use Math.floor() on drawImage coordinates, but do it to save draw time in
case your ratio (or your coordinates) are not integer.
My solution is to append a <div>(position:absolute) covering the canvas. It's not good if canvas has interactive.
I am creating an applicattion to make mindmaps in Canvas and now i have problems with the resize of elements. Initially i have this:
<div id="lienzo">
<canvas id="canvas2" width="1000" height="1000">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
</div>
But any time i want to change the size of the canvas,ie change the width and height of the element canvas.
I have tried remove the canvas with:
$('canvas').remove();
And later create a new element canvas with:
$("<canvas/>",{id:'canvas2'}).appendTo('#lienzo');
$('canvas').width(500);
$('canvas').height(500);
Later i did this i redraw the element in Canvas but this elements look pixelated
Of course, in the new canvas I can´t selected the element.
I tried to change directly measures of Canvas but i have the same problem.
After explaining all, the question is, how could i change the size of Canvas on the fly without that the items in the canvas change. Any idea?
Thanks you for your time
That's because the jQuery .width() and .height() methods change the size of the element with CSS, this is equivalent to scaling it, it doesn't change anything within the canvas element. If you want to change the number of pixels the canvas displays you need to set the .width and .height properties of the canvas element. Try this:
$('#canvas2')[0].width = 500;
$('#canvas2')[0].height = 500;
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).