I'll post a link since theres to much to post here:
http://hem.bredband.net/noor/canvas.htm
My goal is to make the picture fit inside the window with the width of the image being the same as the window, even after resize. If the pictures height becomes to big for the window then the picture should resize itself according to the height and not the width.
Somewhere along my code there is something wrong.. forgive me if this is stupid, i am still learning..
Thanks!
I think this is the behavior you are trying to achieve. I refactored it so you only need to create one Image object (and changed the variable names to English so I could follow the code easier). Hopefully it's clear how the code works. Feel free to ask in the comments if you have any questions about it. The body onload property will need to be changed to "setupBackground();" instead of "draw();" to work with this code.
function setupBackground() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function draw() {
canvas.width = 0;
canvas.height = 0;
var divHeight = div.scrollHeight;
var divWidth = div.scrollWidth;
var yScale = divHeight / img.height;
var xScale = divWidth / img.width;
var newImgHeight = img.height * xScale;
var newImgWidth = divWidth;
if (divHeight >= newImgHeight) {
newImgHeight = divHeight;
newImgWidth = img.width * yScale;
}
canvas.width = divWidth;
canvas.height = divHeight;
ctx.drawImage(img,0,0,newImgWidth,newImgHeight);
}
var img = new Image();
img.onload = function() {
window.onresize = draw;
draw();
}
img.src = 'ad.jpg';
};
As far as I know. You only want to make one call to getContext(). I didn't really analyze the code very much past this point though.
Related
Ok, so, I'm working on a project in HTML5 and JavaScript. I'm trying to resize a Canvas, but it won't work. I don't think it's my browser, though, because I am using the latest version of FireFox. I've also researched this issue for a while, and I am confident I'm doing this correctly. So, I don't know why it won't work.
Here's my Code:
var level = 1;
var levelImg = undefined;
var width = 0;
var height = 0;
var cnvs = document.getElementById("cnvs").getContext("2d");
width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
height = window.innerHeight
|| document.documentElement.cleintHeight
|| document.body.cleintHeight;
cnvs.width = width;
cnvs.height = height;
window.onload = function Init(){
levelImg = document.getElementById("level" + level);
setInterval("Draw()", 3);
}
function Draw(){
//Clear the Screen
cnvs.clearRect(0, 0, width, height);
//Draw stuff
DrawLevel();
}
function DrawLevel(){
cnvs.fillRect(0, 0, 10, 10);
}
Any help is appreciated. Thanks.
First correct all the typos in you code.
Use the browser console to detect errors.
Difference between canvas and the context
var cnvs = document.getElementById("cnvs").getContext("2d");
cnvs variable is not a canvas but the context for the canvas.
Canvas is the element and context is the object used to write in the canvas.
To access the canvas you need to do this:
var canvas = document.getElementById("cnvs");
var cnvs = canvas.getContext('2d'); //context
Now when you are trying to change the canvas with, you use canvas, not cnvs.
canvas.width = width;
canvas.height = height;
SetInterval expects a function and a number value that represents milliseconds.
"Draw()" is a string, not a function, and 3 is a really small number between each time the browser draws on canvas. It works, but it's very inefficient.
Other point about setInterval. Avoid it by using requestAnimationFrame() instead.
Take a look here: setTimeout or setInterval or requestAnimationFrame
Defining var levelImg = undefined has no utility. It can be replaced by var levelImg;
The Problem
I am finding it rather difficult to get my head around this, I am attempting to move an image using the mouse along the X axis only. I am finding it hard to even move the image at all and the many tutorials I have looked at arnt really helping me. Here is what I am trying to say:
As you can see by my beautiful image above I only want to image to move left and right at the bottom of the page.
The Code and the Question
Here is my first attempt, when I try this all the images loaded on the canvas no longer appear making it very hard for me to understand why it isnt working.
<script type="text/javascript">
//Referencing the canvas
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var width = canvas.getAttribute('width');
var height = canvas.getAttribute('height');
//Images
var bggameImage = new Image();
var playerImage = new Image();
var enemyImage = new Image();
var projectileImage = new Image();
var livesImage = new Image();
//Canvas dimensions
var width = 480;
var height = 320;
//Loading in the backgroundImage
bggameImage.src = "Images/bggameImage.png";
bggameImage.onload = function(){
context.drawImage(bggameImage, 0, 0);
}
//Loading in the playerImage
playerImage.src = "Images/playerImage.png";
playerImage.onload = function(){
context.drawImage(playerImage, 165, 240);
}
//Loading in the projectileImage
projectileImage.src = "Images/projectileImage.png";
projectileImage.onload = function(){
context.drawImage(projectileImage, 65, 240);
}
var playerImage = {
x:176,
y:74,
}
function init() {
playerImage.src = "Images/playerImage.png";
//Moving player
myCanvas.addEventListener("mousemove", function (e) {
var bounding_box = myCanvas.getBoundingClientRect();
playerImage = (e.clientX - bounding_box.left) * (myCanvas.width / bounding_box.width) - playerImage.width / 2;
playerImage = (e.clientY - bounding_box.top) * (myCanvas.height / bounding_box.height) - playerImage.height / 2;
}
)
</script>
The whole "function init()" part is what I have just tried but I thought I would include this anyway, I understand that I am loading in the playerImage twice.
You're using the same variable name twice (playerImage), so your image is being overwritten. You're using it for the image and also to store the position. Change the playerImage that's storing x and y to be playerPosition or something like that. Update that variable on your mouse event and then render the image according to that variable's values.
Ultimately, you're going to have to look at a game loop using setTimeout or requestAnimationFrame. So, this will become crucial at that stage. And yes, you shouldn't be loading the player image twice either. Do all of that at the start and only start your game when all your assets have successfully loaded.
For instance...
var playerImage;
var alienImage;
var bulletImage;
var assetCount = 0;
function loadAssets() {
playerImage = new Image();
playerImage.onload = checkAssetsLoaded;
playerImage.src = "assets/images/Brush01.png";
alienImage = new Image();
alienImage.onload = checkAssetsLoaded;
alienImage.src = "assets/images/Brush02.png";
bulletImage = new Image();
bulletImage.onload = checkAssetsLoaded;
bulletImage.src = "assets/images/Brush03.png";
}
function checkAssetsLoaded(event) {
assetCount++;
console.log("An asset has loaded!: " + assetCount);
if (assetCount == 3) {
startGame();
}
}
function startGame() {
// Start your game initialization logic here.
console.log("Game starting!");
}
I'm trying to get an image to be displayed on an HTML5 Canvas while keeping the aspect ratio and having the image reduced (if larger than the canvas). I've look around at some answers but seem to be missing something and wondered if you guys can help.
I'm using the function "calculateAspectRatioFit" suggested by one of the Stackoverflow answers, but it seems to not resize the image for me, as it did in the answer - so I may be doing something wrong :)
Here's my code:
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
var rtnWidth = srcWidth*ratio;
var rtnHeight = srcHeight*ratio;
return { width: rtnWidth, height: rtnHeight };
}
var canvasImage = new Image();
canvasImage.src = "http://www.greenwallpaper.org/backgrounds/simply-green-502085.jpeg";
var ctx = this.getContext('2d');
var parentWidth = self._widgetSize[0];
var parentHeight = self._widgetSize[1];
canvasImage.onload = function() {
var imgSize = calculateAspectRatioFit(canvasImage.width, canvasImage.height, parentWidth, parentHeight);
ctx.clearRect(0, 0, parentWidth, parentHeight);
ctx.drawImage(canvasImage, 0, 0,imgSize.width, imgSize.height);
};
The image is displayed but is larger than the HTML5 Canvas. What I am after is to have the image the same width as the Canvas, and if the height is larger than the height of the canvas then it overflows and is hidden...I just want to fill the width and keep the aspect ratio.
Can anyone help point out what I am missing?
Appreciate your help :)
---Update 30/11---
I've just added the answer to my code and I get the following: (this is the 2nd answer)
var canvasImage = new Image();
canvasImage.src = "http://www.greenwallpaper.org/backgrounds/simply-green-502085.jpeg";
var ctx = this.getContext('2d');
canvasImage.onload = scaleAndDraw(this, ctx, canvasImage);
function scaleAndDraw(canvas, ctx, srcImage) {
// Image is 2560x1600 - so we need to scale down to canvas size...
// does this code actually 'scale' the image? Image of result suggests it doesn't.
var aspect = getAspect(canvas, srcImage);
var canvasWidth = (srcImage.width * aspect);
var canvasHeight = (srcImage.height * aspect);
ctx.drawImage(srcImage, 0, 0, canvasWidth|0, canvasHeight|0);
}
function getAspect(canvas, image) {
return canvas.size[0] / image.width;
}
So the code for displaying the image works, but the image is keeping it's dimensions and is not resizing to the dimensions of the canvas.
Hopefully the image will help you see the problem I am having. Larger images do not seem to rescale to fit in the canvas while keeping aspect ratio.
Any thoughts? :)
Your code works for me as long as I supply sane parentWidth,parentHeight values:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
var rtnWidth = srcWidth*ratio;
var rtnHeight = srcHeight*ratio;
return { width: rtnWidth, height: rtnHeight };
}
var parentWidth = 100; //self._widgetSize[0];
var parentHeight = 50; //self._widgetSize[1];
var canvasImage = new Image();
canvasImage.onload = function() {
var imgSize = calculateAspectRatioFit(canvasImage.width, canvasImage.height, parentWidth, parentHeight);
ctx.clearRect(0, 0, parentWidth, parentHeight);
ctx.drawImage(canvasImage,30,30,imgSize.width, imgSize.height);
};
canvasImage.src = "http://www.greenwallpaper.org/backgrounds/simply-green-502085.jpeg";
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>
I'm currently attempting to dynamically retrieve the location of an image and load it into a html5 canvas. The canvas is in a bootstrap responsive environment hence I never know the actual width of the canvas until the document is ready. Using the code below I've managed to resize the image and canvas to what I require but the image quality is very poor. I'm thinking it is because of the vast reduction in size but again unfortunately I have no control over the size of the original image uploaded.
function load_canvas_image(photo_type, vehicle_index) {
image_location = get_image_location(photo_type, vehicle_index);
var img = new Image();
img.src = image_location;
var canvas = $("#myCanvas")[0];
var canvas_context = canvas.getContext("2d");
canvas_width = canvas.width;
canvas_height = canvas.height;
img.onload = function() {
cur_height = img.height;
cur_width = img.width;
aspect_ratio = cur_width/canvas_width;
new_height = cur_height/aspect_ratio;
canvas.height = new_height;
canvas_context.drawImage(img, 0, 0, canvas.width, canvas.height);
}
};
$(document).on("change", "#add_damage_location", function() {
load_canvas_image($(this).val(), $('#vehicle_index').val());
});
I'm hoping someone knows how to use a similar method to reduce the width and height of an image using a similar method to the above whilst keeping the quality of the image as good as possible, I know to expect some reduction in quality but in it's current state it is unusable.
Thanks in Advance
My web application has many image presentation features, and most of time we need to resize them. I attempted to get its real width and height values by the following fragment code:
var image = new Image();
image.src = IMAGE_URL;
var width = image.width;
var height = image.height;
The above code runs no problem on browsers like Firefox and IE 10, but it returns 0 on Chrome. I guess Chrome doesn't support this.
Can anybody gives me guidance on this?
you need to get width and height after the image loads and understands what its made of.
try:
var image = new Image();
image.onload = function() {
var width = image.width;
var height = image.height;
}
image.src = IMAGE_URL;
hope that helps
Try this
img = new Image();
img.onload = function() {
width = this.width;
height = this.height;
};
Onload help you to get width and height.
You need to wait for the load event, otherwise the dimensions of the image won't be known.
var image = new Image();
image.onload = function() {
var width = image.width;
var height = image.height;
// These values will now be correct.
};
image.src = IMAGE_URL;