I have the following in html:
<img id="MarkingImage"></img>
<canvas id="MarkingCanvas"></canvas>
And on css:
#MarkingCanvas { width: 100%; background-color: #7986CB; height: 96%; }
#MarkingImage { position: absolute; }
And on js:
function LoadImage()
{
var markingImage = new Image();
markingImage.addEventListener('load', function()
{
m_imageWidth = this.naturalWidth;
m_imageHeight = this.naturalHeight;
m_markingCanvasContext.drawImage(markingImage, 0, 0, m_imageWidth, m_imageHeight);
});
markingImage.src = 'PICT0001.JPG';
}
The thing is that this output stretches the image and it's quality gets really poor (see attached "Original" and "Result").
When I debug, I can see that the sizes if my canvas are:
width - 1410
height - 775
The sizes if my image are:
width - 551
height - 335
So my question is: why isn't the image placed in it's original size? I mean, there's enough space on the canvas. Also, why does the image gets stretched, and as a result gets in pretty low quality. Appears like it stretches beyond the size of the canvas.
What am I missing here?
You need to set the canvas width and height dynamically according to the browser window's width and height. also, there is no need to use the image's naturalWidth / naturalHeight.
var m_markingCanvas = document.getElementById('MarkingCanvas');
var m_markingCanvasContext = m_markingCanvas.getContext('2d');
// setting canvas width and height dynamically
m_markingCanvas.width = window.innerWidth;
m_markingCanvas.height = window.innerHeight;
function LoadImage() {
var markingImage = new Image();
markingImage.addEventListener('load', function() {
m_markingCanvasContext.drawImage(this, 0, 0);
});
markingImage.src = 'https://i.stack.imgur.com/a3Wpy.jpg';
}
LoadImage();
<canvas id="MarkingCanvas"></canvas>
Related
I am attempting to resize an image's dimensions, whilst retaining it's aspect ratio. This seems like a very simple task, but I cannot find a rellevent answer anywhere.. (relating to JavaScript's Image() object). I'm probably missing something very obvious. Below is what I am trying to achieve:
var img = new window.Image();
img.src = imageDataUrl;
img.onload = function(){
if (img.width > 200){
img.width = 200;
img.height = (img.height*img.width)/img.width;
}
if (img.height > 200){
img.height = 200;
img.width = (img.width*img.height)/img.height;
}
};
This is to proportionally resize an image before being drawn onto a canvas like so: context.drawImage(img,0,0,canvas.width,canvas.height);.However it would appear I cannot directly change Image()dimensions, so how is it done? Thanks.
Edit: I haven't correctly solved the image proportions using cross-multiplication. #markE provides a neat method of obtaining the correct ratio. Below is my new (working) implementation:
var scale = Math.min((200/img.width),(200/img.height));
img.width = img.width*scale;
img.height = img.height*scale;
clearCanvas(); //clear canvas
context.drawImage(img,0,0,img.width,img.height);
Here's how to scale your image proportionally:
function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){
return(Math.min((maxW/imgW),(maxH/imgH)));
}
Usage:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/balloon.png";
function start(){
canvas.width=100;
canvas.height=100;
var w=img.width;
var h=img.height;
// resize img to fit in the canvas
// You can alternately request img to fit into any specified width/height
var sizer=scalePreserveAspectRatio(w,h,canvas.width,canvas.height);
ctx.drawImage(img,0,0,w,h,0,0,w*sizer,h*sizer);
}
function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){
return(Math.min((maxW/imgW),(maxH/imgH)));
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<h4>Original Balloon image resized to fit in 100x100 canvas</h4>
<canvas id="canvas" width=100 height=100></canvas>
The image dimensions are set in the constructor
new Image(width, height)
// for proportionally consistent resizing use new Image(width, "auto")
or
the context.drawImage()
the arguments are as follows:
context.drawImage(image source, x-coordinate of upper left portion of image,
y-coordinate of upper left portion of image,image width,image height);
simply position the the image with the first two numeric coordinates and then manually adjust the size with the last two (width,height)
//ex.
var x = 0;
var y = 0;
var img = new Image (200, "auto");
img.src = "xxx.png";
context.drawImage(img,x,y,img.width,img.height);
I have this example of a canvas as a div background (I forked it from another example, don't remember where I found it):
http://jsfiddle.net/sevku/6jace59t/18/
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');
var divHeight = document.getElementById('canvas').clientHeight;
var divWidth = document.getElementById('canvas').clientWidth;
function assignToDiv(){ // this kind of function you are looking for
dataUrl = canvas.toDataURL();
document.getElementsByTagName('div')[0].style.background='url('+dataUrl+')'
}
function draw() { // replace with your logic
ctx.fillStyle = "rgb(100, 250, 100)";
ctx.fillRect (10, 10, divWidth-20, divHeight-20);
}
draw()
assignToDiv()
My problem; If I put the dimensions of the div 300 x 150, the canvas does what it is supposed to do. But if I change the dimensions, the canvas is supposed to adapt to the div dimensions. What did I do wrong that this doesn't happen?
PS: I'm a beginner, so please forgive me stupid questions.
It's because if you don't give canvas width and height, it's default to 300x150, so after you get the width and height from div, you should use them to set your canvas' dimensions as well.
Another point worth notice is that you use div.style.background property to set the background image, however, as there's many background related properties (e.g: background-repeat in your jsfiddle, background-position, background-size...), the background can set all of them at once.
When you use div.style.background='url('+dataUrl+')';. It overrides all other background-related properties to initial.
If you want to preserve those properties, you may either reset them after you set style.background, or you can use div.style.backgroundImage to change the background image without affect other background related properties.
jsfiddle
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');
var divHeight = document.getElementById('canvas').clientHeight;
var divWidth = document.getElementById('canvas').clientWidth;
// VVVV After you get WxH, set the canvas's dimension too.
canvas.width = divWidth;
canvas.height = divWidth;
var div1 = document.getElementById('canvas');
var div2 = document.getElementById('canvas2');
function assignToDiv(div){ // this kind of function you are looking for
var dataUrl = canvas.toDataURL();
div.style.background='url('+dataUrl+')'; // This line will overwrite your background settings.
div.style.backgroundRepeat = 'repeat-x'; // Use this to set background related properties after above.
}
function assignToDivAlt(div){ // this kind of function you are looking for
var dataUrl = canvas.toDataURL();
div.style.backgroundImage = 'url('+dataUrl+')'; // Only set the background-image would have same effect.
}
function draw() { // replace with your logic
ctx.fillStyle = "rgb(100, 250, 100)";
// If you don't set WH, then the canvas would be 300x150, and those
// you drawed but out of boundary are clipped.
ctx.fillRect (10, 10, divWidth-20, divHeight-20);
}
draw()
assignToDiv(div1);
assignToDiv(div2);
canvas {display:none;}
div {
width:600px;
height:550px;
border:1px solid grey;
background-repeat:repeat-x;
}
<canvas></canvas>
<div id="canvas"></div>
<div id="canvas2"></div>
I am trying to draw the following image to a canvas but it appears blurry despite defining the size of the canvas. As you can see below, the image is crisp and clear whereas on the canvas, it is blurry and pixelated.
and here is how it looks (the left one being the original and the right one being the drawn-on canvas and blurry.)
What am I doing wrong?
console.log('Hello world')
var c = document.getElementById('canvas')
var ctx = c.getContext('2d')
var playerImg = new Image()
// http://i.imgur.com/ruZv0dl.png sees a CLEAR, CRISP image
playerImg.src = 'http://i.imgur.com/ruZv0dl.png'
playerImg.width = 32
playerImg.height = 32
playerImg.onload = function() {
ctx.drawImage(playerImg, 0, 0, 32, 32);
};
#canvas {
background: #ABABAB;
position: relative;
height: 352px;
width: 512px;
z-index: 1;
}
<canvas id="canvas" height="352" width="521"></canvas>
The reason this is happening is because of Anti Aliasing.
Simply set the imageSmoothingEnabled to false like so
context.imageSmoothingEnabled = false;
Here is a jsFiddle verson
jsFiddle : https://jsfiddle.net/mt8sk9cb/
var c = document.getElementById('canvas')
var ctx = c.getContext('2d')
var playerImg = new Image()
// http://i.imgur.com/ruZv0dl.png sees a CLEAR, CRISP image
playerImg.src = 'http://i.imgur.com/ruZv0dl.png'
playerImg.onload = function() {
ctx.imageSmoothingEnabled = false;
ctx.drawImage(playerImg, 0, 0, 256, 256);
};
Your problem is that your css constraints of canvas{width:512}vs the canvas property width=521will make your browser resample the whole canvas.
To avoid it, remove those css declarations.
var c = document.getElementById('canvas')
var ctx = c.getContext('2d')
var playerImg = new Image()
// http://i.imgur.com/ruZv0dl.png sees a CLEAR, CRISP image
playerImg.src = 'http://i.imgur.com/ruZv0dl.png'
playerImg.width = 32
playerImg.height = 32
playerImg.onload = function() {
ctx.drawImage(playerImg, 0, 0, 32, 32);
};
#canvas {
background: #ABABAB;
position: relative;
z-index: 1;
}
<canvas id="canvas" height="352" width="521"></canvas>
Also, if you were resampling the image (from 32x32 to some other size), #canvas' solution would have been the way to go.
As I encountered this older post for some of my issues, here's even more additional insight to blurry images to layer atop the 'imageSmoothingEnabled' solution.
This is more specifically for the use case of monitor specific rendering and only some people will have encountered this issue if they have been trying to render retina quality graphics into their canvas with disappointing results.
Essentially, high density monitors means your canvas needs to accommodate that extra density of pixels. If you do nothing, your canvas will only render enough pixel information into its context to account for a pixel ratio of 1.
So for many modern monitors who have ratios > 1, you should change your canvas context to account for that extra information but keep your canvas the normal width and height.
To do this you simply set the rendering context width and height to: target width and height * window.devicePixelRatio.
canvas.width = target width * window.devicePixelRatio;
canvas.height = target height * window.devicePixelRatio;
Then you set the style of the canvas to size the canvas in normal dimensions:
canvas.style.width = `${target width}px`;
canvas.style.height = `${target height}px`;
Last you render the image at the maximum context size the image allows. In some cases (such as images rendering svg), you can still get a better image quality by rendering the image at pixelRatio sized dimensions:
ctx.drawImage(
img, 0, 0,
img.width * window.devicePixelRatio,
img.height * window.devicePixelRatio
);
So to show off this phenomenon I made a fiddle. You will NOT see a difference in canvas quality if you are on a pixelRatio monitor close to 1.
https://jsfiddle.net/ufjm50p9/2/
In addition to #canvas answer.
context.imageSmoothingEnabled = false;
Works perfect. But in my case changing size of canvas resetting this property back to true.
window.addEventListener('resize', function(e){
context.imageSmoothingEnabled = false;
}, false)
The following code works for me:
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
};
img.src = e.target.result; // your src
Simple tip: draw with .5 in x and y position. like drawImage(, 0.5, 0.5) :D There you get crisp edges :D
If the source svg is in a responsive environment, how do I use drawImage() to draw a to a given canvas size?
Example: How do I get the svg drawn to a 412.5 x 487.5 canvas, if the original svg is 550 x 650 and it is being viewed on a mobile device (so obviously the svg will be seen smaller than the original size)?
Fiddle
svgToImage(svg2, function(img2){
ctx2.drawImage(img2, 0, 0);
});
function svgToImage(svg2, callback) {
var nurl = "data:image/svg+xml;utf8," + encodeURIComponent(svg2),
img2 = new Image;
img2.onload = function() {
callback(img2);
}
img2.src = nurl;
}
When you SVG has loaded, simply set the canvas size, then draw in the image using the width and height arguments of drawImage.
Note that a bitmap can only take integer values so your canvas has to be either 413x488 or 412x487. If you don't set the canvas size it will default to 300x150 and then stretch to the size you use for style/CSS:
svgToImage(svg2, function(img2){
ctx2.canvas.width = 413; // set canvas size
ctx2.canvas.height = 488;
ctx2.drawImage(img2, 0, 0, 413, 488); // draw SVG/image at same size
});
Updated fiddle
At the end of this question is an SSCCE to display a 24000x12000 Miller projection of satellite imagery on an HTML5 canvas. It has a couple problems:
Rather than showing the entire image in one screen as I desire only a small section of the upper left corner is displayed.
The image suffers from extreme pixellation that should not appear at the scale displayed because the image is very high resolution
The image used is available at Wikimedia. I renamed it "world.jpg".
This is not a normal web application and the large image will not be downloaded during application execution so any advice to not require downloading such a large image is moot.
The application will dynamically zoom into various map areas, thus the large image size.
In the real code I use an external stylesheet and javascript file. I integrated them into the html solely for the SSCCE.
This is the code.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>The Earth</title>
<script type="text/javascript">
function draw() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var map = new Image();
map.src = "world.jpg";
map.onload = function() {
var width = window.innerWidth;
var height = window.innerHeight;
ctx.drawImage(map, 0, 0, width, height);
};
}
</script>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0px;
}
#canvas {
width: 100%;
height: 100%;
position: absolute;
top: 0px;
left: 0px;
background-color: rgba(0, 0, 0, 0);
}
</style>
</head>
<body onload="draw();">
<canvas id="canvas"></canvas>
</body>
</html>
Use the version of context.drawImage that clips and scales the original image:
context.drawImage(
sourceImage,
clipSourceAtX, clipSourceAtY, sourceClipWidth, sourceClipHeight,
canvasX, canvasY, canvasDrawWidth, canvasDrawHeight
)
For example, assume that you are focusing on coordinate [x==1000,y==500] on the image.
To display the 640px x 512px portion of the image at [1000,500] you can use drawImage like this:
context.drawImage(
// use "sourceImage"
sourceImage
// clip a 640x512 portion of the source image at left-top = [1000,500]
sourceImage,1000,500,640,512,
// draw the 640x512 clipped subimage at 0,0 on the canvas
0,0,640,512
);
A demo: http://jsfiddle.net/m1erickson/MtAEY/
Here's the working javascript code, formatted nicely.
function draw() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var map = new Image();
map.src = "world.jpg";
map.onload = function() {
var width = window.innerWidth;
var height = window.innerHeight;
canvas.width=width;
canvas.height=height;
var mapWidth=map.width;
var mapHeight=map.height;
var scale=scalePreserveAspectRatio(mapWidth,mapHeight,width,height);
ctx.mozImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.drawImage(map, 0, 0, mapWidth, mapHeight, 0, 0, mapWidth*scale, mapHeight*scale);
};
}
function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){
return(Math.min((maxW/imgW),(maxH/imgH)));
}
The key is the two lines
canvas.width=width;
canvas.height=height;
Simply setting these to 100% in CSS doesn't work, the 100% is apparently not 100% of the inner dimensions of the window as I assumed. Since these dimensions are dynamic they must be set via JS not CSS.