I am currently trying to work on this script, which was created by someone else. Yes, I grabbed it, yes I will give credits.
The problem I am having, is trying to center the text even if the window has been resized. When you move the cursor on the text, it explodes randomly. When I resize the window, I need that same text (and those exploded characters) to move. I can easily just put new text in using fillText(), but then I replace the exploded characters.
Obviously I have tried this in my example:
window.onresize = function(event) {
reload(canvas_id);
}
var reload = function(canvas_id) {
canvas = document.getElementById(canvas_id);
context = canvas.getContext("2d");
canvas.width = window.innerWidth;
}
This resizes the canvas perfectly, but the text won't be centered anymore. To center the text when I place it, I do this:
(window.innerWidth / 2) - (Math.round(bgContext.measureText(keyword).width/2))
bgContext being the canvas.getContext("2d"); obviously.
Here's a JSFiddle showing this issue: http://jsfiddle.net/2e8o5db8/1/
First, tell canvas to draw text aligned from a center X rather than the default left-aligned
context.textAlign = 'center';
And then set the x,y in fillText to the center of the canvas.
fillText('Hello', canvas.width/2, 50);
By using canvas.width/2 you will redraw the text at center-canvas even if the canvas is resized.
You will have to redraw the text after using canvas.width=... because the canvas contents will automatically be cleared.
Related
I have a canvas with an image that fills the canvas. This works fine but I would like to have the canvas be full width of the window. At the moment the canvas is the width of the image I put in it.
I've tried the following at the bottom of my script:
function resizeCanvas() {
canvas.setHeight(img.height);
canvas.setWidth(window.innerWidth);
canvas.renderAll();
}
resizeCanvas();
But this does not work.
I've also tried giving the canvas element 100% width in its paramaters and with css, both with no success.
Codepen with working example:
https://codepen.io/twan2020/pen/YzpeEEr
If you increase your screen size the image stops after a while instead of keeping full width of the browser window.
Is this possible? With keeping all objects in their place?
It was not easy to fix but i found some documentation that could make it work.
First edit the code to realWidth and add var realWidth = window.innerWidth;
and then for setting the background remove your current code and add
fabric.Object.NUM_FRACTION_DIGITS = 10;
fabric.Image.fromURL(source, function(img) {
img.scaleToWidth(canvas.width);
canvas.setBackgroundImage(img);
canvas.requestRenderAll();
});
this should fix the problem, and the backgound will take the full size of the screen.
Update for the new calculation of the circle position.
is equal to Newposition= oldPosition * (newWidth / oldWidth)
Here you can see that it work https://codepen.io/AlenToma/pen/ExNEooX
So we all know the issue with shapes being drawn with a slightly blurred stroke. I was able to fix it without further problems when using plain js and canvas with following methods:
context.sRect=function(x,y,w,h){
x=parseInt(x)+0.50;
y=parseInt(y)+0.50;
this.strokeRect(x,y,w,h);
}
context.fRect=function(x,y,w,h){
x=parseInt(x);
y=parseInt(y);
context.fillRect(x,y,w,h);
}
However, when using easeljs stage, these methods dont have any impact at all and the shapes stay blurred. I also tried offsetting x and y as well as width and height by -.5 when using drawRect(); That didnt work either. The last thing I tried was setting stage.regX and stage.regY to -.5 which did change the output but only to an altered blur (slightly more blurry).
Did I miss something?
PS: I need the canvas to always have the same width and height (200 * 200) but at the same time always fill the screen. I accomplish this by always setting canvas.width/height to 200 and the css of canvas to 100%.
Simple answer: you can't.
When you use CSS to scale a canvas, you can think of it as scaling each pixel on the canvas individually. Because of this, you are going to need to counteract the antialiasing of the browser itself.
To accurately counteract antialiasing in raster graphics, you always need more space than the container, simply because of the quantisation of information in pixels. If you do want your canvas to hold a fixed amount of information (200x200 pixels), this is not possible.
What you can still do is use that canvas as the model, but not the view ;)
If I did not want antialiasing of a fix-sized canvas over a variable space, I'd create another canvas whose size won't depend on the css, but on js events (look into window resize event listener and window.innerWidth, window.innerHeight), then draw the "model" original canvas on it while disabling ctx.imageSmoothingEnabled (= false), so that you'll get the needed result.
Here's a minimal example:
var canvasModel = document.createElement( 'canvas' ), // your current canvas
canvas = document.getElementById( 'view-canvas' ), // displaying on the screen
ctxModel = canvasModel.getContext( '2d' ),
ctx = canvas.getContext( '2d' );
ctx.imageSmoothingEnabled = false;
// all of your stuff that you're currently doing goes here
...
// every time you update the 200x200 canvas, you do this:
ctx.drawImage( canvasModel, 0, 0, w, h );
I am trying to create my first website using the p5.js library, with the end goal being an online digital portfolio. I am currently working on a splash screen, in which I have some large title text filling the center of the screen on a simple black background, which actively resizes to fill the window.
I would like to place a simple doodle in the background to add some interest. My challenge is that I would not like this doodle to draw on top of my text, but instead place it underneath my text. Initially I was thinking of infinitely redrawing the text so it stays at the top, however I have deduced there is no way to do this while still animating something beneath it.
My knowledge of HTML / CSS is minimal, however I was thinking of making the background of the title sketch transparent, a separate sketch with the doodle, and use the z index property in CSS to place the doodle beneath the title, is this even possible?
Thanks!
Further edits based on recommendations:
function preload() {
myFont = loadFont('assets/HighTide.otf');
}
function setup() {
canvas = createCanvas(window.innerWidth, window.innerHeight);
title = text("Welcome", width/2, height/2);
background(30);
fsize = window.innerHeight/4;
pg = createGraphics(window.innerWidth, window.innerHeight);
}
function draw() {
background(30);
pg.fill(random(0,255), random(0,255), random(0,255));
//pg.translate(width/2, height/2);
pg.ellipse(random(window.innerWidth), random(window.innerHeight), 60, 60)
image(pg, 0, 0);
textFont(myFont);
textSize(fsize);
textAlign(CENTER);
fill(255);
text("Welcome", width/2, height/2);
}
window.onresize = function() {
var w = window.innerWidth;
var h = window.innerHeight;
canvas.size(w,h);
fsize = window.innerHeight/4;
title.textSize(fsize);
width = w;
height = h;
}
It depends on exactly how you're drawing everything, but if you're doing this all in P5.js then you've already described exactly what you need to do.
Step 1: Each frame, clear out old frames by calling the background() function.
Step 2: Then draw your doodle.
Step 3: Finally, draw your text. Since you're drawing the text after the doodle, it shows up "on top" of the doodle.
This is how most P5.js sketches work: every frame, you clear out the old frames and then draw the next frame.
Edit: If you need a sketch that doesn't clear out old frames but still shows two different layers (your doodle and your text), then what you could do is draw your doodle to a buffer, then draw that buffer each frame, then draw the text on top of the buffer. Check out the createGraphics() function in the reference.
I am rendering a QR code to a div, however the div is hidden. When I copy the canvas to an image with the correct size, the image is blurred.
var children = $("#trial").children();
var canvas = children[0];
var ctx = canvas.getContext('2d');
//ctx.scale(3,3);
var img = new Image();
img.width = "300";
img.src = canvas.toDataURL();
$("#imagetrial").html(img);
I have tried scaling it as in the commented code, but the raw image turns out small, and when stretching the image it is blurred. If the div is not hidden, the code works correctly, but I cannot show the canvas, I am only interested in the data url which is passed on to a pop up print page.
Does anyone know a way to adjust the canvas size in the hidden div so that it copies correctly?
You can set the width of a canvas (onscreen or offscreen) like this:
canvas.width = 300;
You may be running into some subpixel issues regardless of canvas and image size matching.
Every canvas applies anti aliasing that CANNOT be turned off if the image you're generating on the canvas contains graphical elements or images drawn at sub pixel coordinates.
See this article: http://sebleedelisle.com/2011/02/html5-canvas-sprite-optimisation
I ended up hiding the div by placing it offscreen, then the canvas gets copied correctly.
I am making for school a star catching game.
I want the enviroment to change dynamicly so that when i resize browser windows the game will resize with it.
I got the following running code:
http://jsfiddle.net/xigolle/yA74f/
The only problem with that is that the mouse isn't center on the witch.
What is the best way for me to get the mouse on the center on every size?
The problem lays for sure in this part:
ctx.drawImage(img, this.x, this.y, canvas.width/10, canvas.height/10);
The size of the browser window i get from a event listener who activates when i resize.
And the value is put in canvas.width and canvas.height.
I hope you guys can help me :)
For any more question or unclearance please ask :)
You have two problems
The first is your use of drawImage
ctx.drawImage(img, this.x, this.y, canvas.width/10, canvas.height/10);
This is going to rescale the witch image in a way that does not keep the proportions, which is why when resizing the window the witch either squishes or expands
You should resize the image based on a ratio of the original image size and original canvas size. Then use that ratio times the new canvas size to get the right image size.
//Original canvas width/height
var initialWidth = 500, initialHeight = 500;
var initialImgWidth = 120, initialImgHeight = 65;
var wRatio = initialImgWidth/initialWidth, hRatio = initialImgHeight/initialHeight;
...
ctx.drawImage(img, this.x, this.y, canvas.width*wRatio, canvas.height*hRatio);
Now that we have the image resize resolved now we can center the image on the mouse
Now to center you have to take the mouse x/y and minus each with 1/2 of width/height of the rescaled witch respectively
Witch.x = event.pageX-((canvas.width*wRatio)/2);
Witch.y = event.pageY-((canvas.height*hRatio)/2);
JSFiddle
EDIT
My rescale calculations were wrong, for now to scale the image for now just scale it by its original dimensions
var imgWScale = initialImgWidth/2;
var imgHScale = initialImgHeight/2;
...
ctx.drawImage(img, this.x, this.y, imgWScale,imgHScale);
...
Witch.x = event.pageX-(imgWScale/2);
Witch.y = event.pageY-(imgHScale/2);
Just remember to center just get the images width/height and divide in half and then take that from the mouse coordinates.