Canvas drawing gets distorted when resizing canvas - javascript

I'm implementing drawing on canvas with html5 and javascript.
If I dont set canvas width and height manually ( leave it default) , my drawing works good.
However, when I set canvas size either from css or javascript, my drawing looks like distorted. The line starts drawing little bit away from the line, and the line looks distorted.
Here is the code for mousedown event.
if (mouseDown)
{
previousX = currentX;
previousY = currentY;
currentX = e.clientX - canvas.offsetLeft;
currentY = e.clientY - canvas.offsetTop;
ctx.beginPath();
ctx.moveTo(previousX, previousY);
ctx.lineTo(currentX, currentY);
ctx.strokeStyle = color;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
}

You must set the size of canvas using its correct properties/attributes.
Canvas is an element with a bitmap. If you use CSS or style you will only scale the element, not the bitmap. The result is a blurry image.
Set correct size by doing this (and CSS is not necessary normally):
<canvas width=800 height=800></canvas>
or in JavaScript:
canvas.width = 800; // example size
canvas.height = 800;
If you use CSS, either using a rule or the style attribute in the element, to scale the canvas you will only scale a 300x150 pixel bitmap to something else which will give bad quality. Always scale the bitmap and then redraw (as the canvas will be cleared).

The canvas API is only for drawing in raster. That's why it doesn't retain clarity when it resizes. It's to be expected.
If you'd want to produce vector, you'd have to use SVG (Scalable Vector Graphics) instead. But the SVG doesn't support drawing. Producing SVG is basically through XML, so it's not flexible the same way as the canvas API is.
Here's a library that will help you accomplish drawing to the canvas in vector:
http://paperjs.org/
"Paper.js is an open source vector graphics scripting framework that runs on top of the HTML5 Canvas."
Here's another thread which enumerates more options:
HTML5 Canvas Vector Graphics?

Related

How can I make elements inside the canvas responsive?

I am trying to build a game using HTML5 canvas.
The canvas takes the full width and height of the browser.
canvas.height = innerHeight;
canvas.width = innerWidth;
How can I make the elements inside the canvas, like player, obstacles etc. responsive?
I know doing something like
addEventListener("resize", () => {
canvas.width = innerWidth;
canvas.height = innerHeight - 100;
});
will make the canvas responsive. But what about the elements drawn to the canvas?
One approach is to use two canvases:
The onscreen canvas, which you make responsive by setting its width and height to the viewport width and height (as you do in your resize event listener)
A second canvas element which you create using Javascript. This will have width and height dimensions that will never change (say 600px by 400px), which means you can render your game elements onto it with confidence.
Render the game on this second canvas and then, at the end of each RequestAnimationFrame cycle, copy it onto the first canvas using the ctx.drawImage() function. At this point you can do calculations to get the whole of your second canvas to fit into the first canvas leaving gaps either at the top/bottom, or on the left/right edges.
As a bonus, this will also allow your users to zoom/pan across your second canvas - if your game calls for that sort of thing.
Method 1
This is if you’d like the pixels to scale as well (like with pixel art)
If you want the drawings to scale as well, then change the canvas’s css height and width values, not the width and height attributes. Like this:
canvas.style.height = innerHeight + ‘px’;
canvas.style.width = innerWidth + ‘px’;
This will scale all the drawings as well.
However, using this alone, all drawings will be scaled using interpolation, giving a fuzzy look. To prevent that, add this:
canvas {
image-rendering: optimizeSpeed;
image-rendering: -moz-crisp-edges;
image-rendering: -webkit-optimize-contrast;
image-rendering: -o-crisp-edges;
image-rendering: pixelated;
-ms-interpolation-mode: nearest-neighbor;
}
This will make the browser scale it using nearest-neighbor instead.
Method 2
This method will scale all of the drawings, but will not scale pixels, and will not make it look too pixely nor fuzzy.
Like you originally did, set the width and height attributes of the canvas:
canvas.height = innerHeight;
canvas.width = innerWidth;
But create variables representing how much the canvas was scaled:
var scaleW = newWidth / oldWidth;
var scaleH = newHeight / oldHeight;
Then, add these to your drawing so you don’t have to manually scale every value:
ctx.save(); // saves the ctx
ctx.scale(scaleW, scaleH); // scales the drawings
// all your drawing ...
ctx.restore(); // restores the ctx, removing the scale
Sorry if the first didn’t work, hopefully the second should.

avoid distortion drawing lines in canvas

I need help trying to represent lines in a canvas. The lines are drawn with the mouse and my problem comes when I try to make the canvas responsive.
When I am drawing lines in the desktop you don't really see the distortion, but when the canvas is loaded in a mobile and I draw an horizontal line, turns out that it keeps the "round shape" of the point, but in vertical lines the point narrows on the sides so the line gets narrower. Because is difficult to explain I show up a picture where I can ilustrate you better:
I also include an example of the code I am using, so you have a better idea of what I am talking about:
//getting the mouse coords
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
scaleX = canvas.width / rect.width, /*relationship bitmap vs. element for X*/
scaleY = canvas.height / rect.height; /*relationship bitmap vs. element for Y*/
return {
x: Math.round((evt.clientX - rect.left)*scaleX),
y: Math.round((evt.clientY - rect.top)*scaleY)
};
}
and in the context of the canvas I say:
ctx.lineJoin="round";
The full code is here:
https://jsfiddle.net/rhwcbwwL/20/
Thank you in advance!!

Mouse on center of moving image on canvas

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.

Zooming on HTML5 <canvas> and no pixelation for text?

Let's put some text on a HTML5 <canvas> with
var canvas = document.getElementById('myCanvas'),
ctx = canvas.getContext('2d'),
ctx.textBaseline = 'top';
ctx.textAlign = 'left';
ctx.font = '14px sans-serif';
ctx.fillText('Bonjour', 10, 10);
When zooming the canvas on text, one can see pixelation.
Is there a way of zooming on a canvas without having pixelation on text ?
When you fillText on the canvas, it stops being letters and starts being a letter-shaped collection of pixels. When you zoom in on it, the pixels become bigger. That's how a canvas works.
When you want the text to scale as a vector-based font and not as pixels, don't draw them on the canvas. You could create <span> HTML elements instead and place them on top of the canvas using CSS positioning. That way the rendering engine will render the fonts in a higher resolution when you zoom in and they will stay sharp. But anything you draw on the canvas will zoom accordingly.
Alternatively, you could override the browsers zoom feature and create your own zooming algorithm, but this will be some work.
When the user zooms in or out of the window, the window.onresize event handler is triggered. You can use this trigger to adjust the width and the height of the canvas css styling accordingly (not the properties of the canvas. That's the internal rendering resolution. Change the width and height attributes of the style which is the resolution it is scaled to on the website).
Now you effectively disabled the users web browser from resizing the canvas, and also have a place where you can react on the scaling input events. You can use this to adjust the context.scale of your canvas to change the size of everything you draw, including fonts.
Here is an example:
<!DOCTYPE html>
<html>
<head>
<script type="application/javascript">
"use strict"
var canvas;
var context;
function redraw() {
// clears the canvas and draws a text label
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
context.font = "60pt sans-serif";
context.fillText("Hello World!", 100, 100);
}
function adjustSize() {
var width = window.innerWidth;
var height = window.innerHeight;
// resize the canvas to fill the whole screen
var style = canvas.style;
style.width = width + "px";
style.height = height + "px";
// backup the old current scaling factor
context.save();
// change the scaling according to the new zoom factor
context.scale(1000 / width, 1000 / height);
// redraw the canvas
redraw();
// restore the original scaling (important because multiple calls to scale are relative to the current scale factor)
context.restore();
}
window.onload = function() {
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
adjustSize();
}
window.onresize = adjustSize;
</script>
</head>
<body>
<canvas id ="myCanvas" width = 1000 height = 1000 ></canvas>
</body>
</html>
If you only need to scale text you can simply scale the font size.
A couple of notes on that however: fonts, or typefaces, are not just straight forward to scale meaning you will not get a smooth progress. This is because fonts are often optimized for certain sizes so the sizes in between so to speak are a result of the previous and next size. This can make the font look like it's moving around a little when scaled up and is normal and expected.
The approach here uses a simply size scale. If you need an absolute smooth scale for animation purposes you will have to use a very different technique.
The simple way is:
ctx.font = (fontSize * scale).toFixed(0) + 'px sans-serif';
An online demo here.
For animation purposes you would need to do the following:
Render a bigger size to an off-screen canvas which is then used to draw the different sizes
When the difference is too big and you get problems with interpolation you will have to render several of these cached text images at key sizes so you can switch between them when scaling factor exceeds a certain threshold.
In this demo you can see that at small sizes the pixels gets a bit "clumpy" but otherwise is much smoother than a pure text approach.
This is because the browser uses bi-linear interpolation rather than bi-cubic with canvas (this may or may not change in the future) so it's not able to interpolate properly when the difference gets to big (see below for solution with this issue).
The opposite happens at big sizes as the text gets blurry also due to interpolation.
This is where we would have to switch to a smaller (or bigger) cached version which we then scale within a certain range before we again switch.
The demo is simplified to show only a single cached version. You can see halfway through that this works fine. The principle would be in a full solution (sizes being just examples):
(Update Here is a demo of a switched image during scale).
-- Cached image (100px)
-- Draw cached image above scaled based on zoom between 51-100 pixels
-- Cached image (50px) generated from 100px version / 2
-- Draw cached image above scaled based on zoom between 26-50 pixels
-- Cached image (25px) generated from 50px version / 2
-- Draw cached image above scaled based on zoom between 1-25 pixels
Then use a "sweet spot" (which you find by experiment a little) to toggle between the cached versions before drawing them to screen.
var ctx = canvas.getContext('2d'),
scale = 1, /// initial scale
initialFactor = 6, /// fixed reduction scale of cached image
sweetSpot = 1, /// threshold to switch the cached images
/// create two off-screen canvases
ocanvas = document.createElement('canvas'),
octx = ocanvas.getContext('2d'),
ocanvas2 = document.createElement('canvas'),
octx2 = ocanvas2.getContext('2d');
ocanvas.width = 800;
ocanvas.height = 150;
ocanvas2.width = 400; /// 50% here, but maybe 75% in your case
ocanvas2.height = 75; /// experiment to find ideal size..
/// draw a big version of text to first off-screen canvas
octx.textBaseline = 'top';
octx.font = '140px sans-serif';
octx.fillText('Cached text on canvas', 10, 10);
/// draw a reduced version of that to second (50%)
octx2.drawImage(ocanvas, 0, 0, 400, 75);
Now we only need to check the sweet spot value to find out when to switch between these versions:
function draw() {
/// calc dimensions
var w = ocanvas.width / initialFactor * scale,
h = ocanvas.height / initialFactor * scale;
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (scale >= sweetSpot) {
ctx.drawImage(ocanvas, 10, 10, w, h); /// use cached image 1
} else {
ctx.drawImage(ocanvas2, 10, 10, w, h); /// use cached image 2
}
}
So why not just draw the second cached image with a font? You can do that but then you are back to the issue with fonts being optimized for certain sizes and it would generate a small jump when scaling. If you can live with that then use this as it will provide a little better quality (specially at small sizes). If you need smooth animation you will have to reduce a larger cached version in order to keep the size 100% proportional.
You can see this answer on how to get a large image resized without interpolation problems.
Hope this helps.

Canvas element, draw circle resize

I am SLOWLY trying to create the breakout game to get more familiar with javascript.
I am trying to re size the canvas element according to the window size, but notice the
circle I am rendering re sizes automatically according to the size of the canvas. How would i render the size of the circle independently from the size of the canvas?
//resize canvas
$(function(){
$("#canvas").width($(window).width());
});
//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");
//draw a circle
ctx.beginPath();
ctx.arc(75, 75, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
here is my fiddle:
http://jsfiddle.net/z25q7/3/
Thank you!
Change the canvas' width property directly, not its CSS style.width (which is what jQuery does):
$("#canvas")[0].width = $(window).width();
More information here: Size of HTML5 Canvas via CSS versus element attributes

Categories