Reputation: 405
I am trying to create a responsive canvas that has a background image. I created a codepen that has the problem here: http://codepen.io/eternalminerals/pen/avZBOr
I am trying to make this canvas responsive, meaning that when I resize the window, the image in the background also resizes, but instead the image completely disapears when you resize the window.
Any help would be appreciated! The codepen has the problem in it. Thanks.
Here is the javascript:
$(document).ready(function( $ ) {
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = 934;
canvas.height = 622;
var background = new Image();
var width = 200;
var height = 137;
background.src = "http://eternalminerals.com/wp-content/uploads/2014/03/mg-balance2.gif";
background.onload = function(){
ctx.drawImage(background,0,0,canvas.width, canvas.height);
}
});
$(document).ready(function( $ ) {
//Get the canvas &
var c = $('#canvas');
var ct = c.get(0).getContext('2d');
var container = $(c).parent();
//Run function when browser resizes
$(window).resize( respondCanvas );
function respondCanvas(){
c.attr('width', $(container).width() ); //max width
c.attr('height', $(container).height() ); //max height
//Call a function to redraw other content (texts, images etc)
}
//Initial call
respondCanvas();
});
Upvotes: 0
Views: 243
Reputation: 728
It looks like you might need to redraw the image upon window resize.
ct.drawImage(background, 0, 0, $(container).width(), $(container).height());
I have an example that will keep your image visible still: http://codepen.io/anon/pen/XmKNXG
However, there is another problem where the container height keeps increasing. I am not sure why.
Upvotes: 1