I've got the following piece of code:
HTML
<img src="http://hollywoodteenonline.com/wp-content/uploads/2011/12/justin_bieber_someday_fragrance_dree_hemingway.jpg" id="imagem"/>
<canvas id="mycanvas">
CSS
#mycanvas{
height:200px;
width: 200px;
border: solid;
color: black;
}
#imagem{
height:200px;
width: 200px;
}
Javascript
var canvas = document.getElementById("mycanvas"),
ctx = canvas.getContext("2d"),
img = document.getElementById("imagem");
ctx.drawImage(img,0,0);
As you can see, the canvas doens't follow up the resize of the original image. As the code is written it "should" show all of the source but resized to de designated canvas. Is there any way to go around this?
Issues
First issue is that you don't set a size for your canvas element by using its properties. This is the only way you can affect the content of the canvas and not settings it means it will default to 300 x 150 pixel no matter what you set as CSS rule for it.
Second issue is that you are using CSS to the set size. This will affect the element itself, not the content of the canvas. Technically this isn't wrong in case you want to scale the canvas as an image, but it won't do anything for the canvas and the result is that you just scale the 300x150 pixels around.
The third issue, if the image is of different size than 300x150 it won't fit the canvas (too small or get cropped if too big).
Solutions
One solution is to set the size of the canvas to the size of the image and paint the image in:
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
Now you can resize the canvas (as an image using CSS) if you want.
Or you can scale the image using the size of the canvas (remove the CSS rule; and you still need to set a size for canvas):
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
LIVE DEMO HERE
You also need to take care in how you invoke your script. For images to work with canvas they need to be loaded. As they load asynchronous you need to handle load events one way or another (ie. inside a window.onload in this case).
Related
I'm having a problem with loading image into canvas - the image is somehow scaled.
Background: I've got several canvases on my web page, I want to load images into them. When constructing, I'm not sure about the dimension, because the size depends on the screen size.
So I create div and canvas, use css to have it in the size that I want it to have and print an image onto the canvas. There would couple more things to do with the image (i.e. decide based on the ratio if I need to center it vertically or horizontally), but those are not really important at this point. The problem is that the image is rendered "zoomed".
Example: the javascript piece is here:
$("canvas").each(function() {
var context = $(this)[0].getContext('2d');
var img = new Image;
img.src = 'http://i67.tinypic.com/n38zdv.jpg';
$(img).load(function() {
context.drawImage(this, 0, 0);
});
//img will print 400 (correct, thats the width of the img)
//canvas will print based on the screen size (correct)
//img displayed in the canvas shows 300px out of 400px, it's zoomed (not correct)
$(this).parent().append(
'img width: '+img.width+
', canvas width: '+$(this).width());
});
I put the whole example with HTML and CSS to https://jsfiddle.net/7zdrfe58/11/.
I'm trying on Mac. Safari and Chrome work the same (i.e. with the zoom).
I would very appreciate help with this!! Thanks a lot
drawImage lets you specify the width and height of the image. You can get the canvas width like so:
$("canvas").each(function() {
var canvas = this;
var context = canvas.getContext('2d');
var img = new Image;
img.src = 'http://i67.tinypic.com/n38zdv.jpg';
$(img).load(function() {
context.drawImage(this, 0, 0, canvas.width, canvas.height);
});
});
Check out your working code here:
https://jsfiddle.net/ucxdLsq9/
The documentation of the drawImage signatures can be found here:
https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/drawImage
Give proper width and height to drawImage.
context.drawImage(this, 0, 0 ,300 ,160);
Updated Fiddle
Been playing around with canvas lately, but it behaves oddly at different sizes.
Here's my code:
HTML: <canvas></canvas>
CSS: canvas { width:300px; height:50px; }
JS:
var c = document.querySelector("canvas"),
ctx = c.getContext("2d");
ctx.fillRect(10,10,50,50); // fill a 50x50 square at pos (10,10)
At canvas size 300x50, the following is drawn:
At canvas size 100x200, the following is drawn:
It's clear that one pixel does not actually mean one pixel - am I doing something wrong?
Don't use CSS to change the size of the canvas. Instead change the size of the element:
c.width=300;
c.height=50;
That's because when you resize with CSS you're "stretching" the pixels. When you change the size of the element itself, you are actually adding/subtracting pixels.
I'm trying to draw an image onto a canvas, like this:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
ctx.drawImage(img,0,0,100,100,0,0,200,200);
The canvas is 200px by 200px and the image is much bigger (but styled at 200px by 200px too)
As you can see in the jsfiddle the canvas doesn't show the image (I was expecting a part of the image).
My understanding of drawImage (as is described here) goes like this:
"0,0,100,100" defines a rectangle on the image which is the part that is drawn onto the canvas. 0,0 defines the top/left corner and 100,100 are the widths of the sides.
This rectangle is drawn onto the canvas inside the rectangle defined by 0,0,200,200
Any suggestions what goes wrong here ?
You image is actually 585 x 585 so what you are doing is to clip a corner from it (which is blank) and draw it onto canvas which of course won't show anything.
Scaling the image with CSS doesn't actually change its size. It only scales it for display.
So what you need to do is to use the original size of the image as basis. If you simply want to scale it down to fit in canvas you can do:
ctx.drawImage(img, 0, 0, 200, 200);
The same goes for canvas. Don't scale canvas using CSS but set the width and height properties/attributes or else the canvas will default to 300x150 (which is then scaled by your css):
<canvas width=200 height=200 ...>
Modified fiddle
Set the width and height on the canvas and draw the image at the same dimensions. Updated your fiddle - http://jsfiddle.net/FQhGg/2/
var c=document.getElementById("myCanvas"),
ctx=c.getContext("2d"),
img=document.getElementById("scream"),
width = img.width,
height = img.height;
c.width = width;
c.height = height;
ctx.drawImage(img,0,0,width,height);
The HTML5 <canvas> element does not accept relative sizes (percent) for its width and height properties.
What I'm trying to accomplish is to have my canvas sized relative to the window. This is what I've come up with so far, but I'm wondering if there is a better way that is:
Simpler
Does not require wrapping the <canvas> in a <div>.
Not dependent on jQuery (I use it to get the width/height of the parent div)
Ideally, doesn't redraw on browser resize (but I think that might be a requirement)
See below for the code, which draws a circle in the middle of the screen, 40% wide up to a maximum of 400px.
Live demo: http://jsbin.com/elosil/2
Code:
<!DOCTYPE html>
<html>
<head>
<title>Canvas of relative width</title>
<style>
body { margin: 0; padding: 0; background-color: #ccc; }
#relative { width: 40%; margin: 100px auto; height: 400px; border: solid 4px #999; background-color: White; }
</style>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
function draw() {
// draw a circle in the center of the canvas
var canvas = document.getElementById('canvas');
var relative = document.getElementById('relative');
canvas.width = $(relative).width();
canvas.height = $(relative).height();
var w = canvas.width;
var h = canvas.height;
var size = (w > h) ? h : w; // set the radius of the circle to be the lesser of the width or height;
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(w / 2, h / 2, size/2, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
}
$(function () {
$(window).resize(draw);
});
</script>
</head>
<body onload="draw()">
<div id="relative">
<canvas id="canvas"></canvas>
</div>
</body>
</html>
The canvas width and height attributes are separate from the same canvas's width and height styles. The width and height attributes are the size of the canvas's rendering surface, in pixels, whereas its styles choose a location in the document where the browser should draw the content from the rendering surface. It just so happens that the default value for the width and height styles, if they're not specified, is the rendering surface's width and height. So you're right about #1: there's no reason to wrap it in a div. You can set percentage values for all of the styles on your canvas element, just like any other element.
For #3, it's pretty easy (and cross-browser) to get the size of things with clientWidth and clientHeight, as long as you're not using padding on your canvas element.
I coded up the slightly simplified version here.
For #4, you're right about being out of luck. It's possible to check before setting width and height and leave the canvas alone if it doesn't need resizing, which would eliminate some of the redraws, but you can't get rid of all of them.
EDIT: Portman pointed out I messed up the centering style. Updated version here.
Like said by sethobrien a canvas element has TWO pairs width/height of attributes.
canvas.width / canvas.height are about the size in pixel of the buffer that will contains the result of drawing commands.
canvas.style.width / canvas.style.height are about the size used to show the canvas object in the browser window and they can be in any of the units supported by css.
You can indeed set canvas.width and canvas.height just once, do the drawing in the canvas, setting the style size parameters in percentage and then forget about redrawing the canvas content. Of course this means that the browser will just do the scaling itself like for a regular image loaded from the network so the visible result will show pixel scaling artifacts.
You need to redraw the canvas content after the resize of the canvas element only if you want pixel-perfect results.
Alright. Here is the technique that i ve used to implement the same.
Suppose you have the canvas height=400, for the window's height=480, and you want to change the height of it relatively if the window's height changes to 640.
canvas = document.getElementById("canvas");
canvas.height=window.innerHeight*400/480;
p.s: do not initialize the height of the canvas inside the html tag.
Make use of 'window.innerHeight' (which returns the height of the browser's window.. similarly 'window.innerWidth') any where you want to calculate the relative positions on the window.
Hope you got what you needed.
I'm trying to allow the user to draw a rectangle on the canvas (like a selection box). I'm getting some ridiculous results, but then I noticed that even just trying the code from my reference here, I get huge fuzzy lines and don't know why.
it's hosted at dylanstestserver.com/drawcss. the javascript is inline so you can check it out. I am using jQuery to simplify getting the mouse coordinates.
The blurry problem will happen if you use css to set the canvas height and width instead of setting height and width in the canvas element.
<style>
canvas { height: 800px; width: 1200px; } WRONG WAY -- BLURRY LINES
</style>
<canvas height="800" width="1200"></canvas> RIGHT WAY -- SHARP LINES
For some reason, your canvas is stretched. Because you have its css property width set to 100%, it is stretching it from some sort of native size. It's the difference between using the css width property and the width attribute on the <canvas> tag. You might want to try using a bit of javascript to make it fill the viewport (see jQuery .width()):
jQuery(document).ready(function(){
var canvas = document.getElementById('drawing');
canvas.width(($(window).width()).height($(window).height());
var context = canvas.getContext('2d');
//...
The way I do it is to set the canvas element to a width and height in the css, and then set the canvas.width = canvas.clientWidth and canvas.height = canvas.clientHeight
var canvas = document.getElementById("myCanvas");
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
var context = canvas.getContext("2d");
You haven't indicated canvas size in pixels, so it is scaled up. It is 300x150 here. Try setting the width, height
On retina displays you also need to scale (in addition to the accepted answer):
var context = canvas.getContext('2d');
context.scale(2,2);
The css sizing issue mentioned in these comments is correct, but another more subtle thing that can cause blurred lines is forgetting to call make a call to context.beginPath() before drawing a line. Without calling this, you will still get a line, but it won't be smoothed which makes the line looks like a series of steps.
I found the reason mine was blurry was that there was a slight discrepancy between the inline width and the CSS width.
I have both inline width/height parameters AND css width/height assigned to my canvas, because I need to keep its physical dimensions static, while increasing its inline dimensions for retina screens.
Check yours are the same if you have a situation like mine.