Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  195] [ 2]  / answers: 1 / hits: 23283  / 11 Years ago, mon, january 13, 2014, 12:00:00

I have a canvas object that I want to put an image in for a web application. I can get the image loaded, but I've run into 2 problems: The image won't stretch to the canvas, and the canvas won't stretch to cover the entire div in any browser but Firefox.



http://jsfiddle.net/LFJ59/1/



var canvas = $(#imageView);
var context = canvas.get(0).getContext(2d);

$(document).ready(drawImage());
$(window).resize(refreshCanvas());

refreshCanvas();

function refreshCanvas() {
//canvas/context resize
canvas.attr(width, $(window).get(0).innerWidth / 2);
canvas.attr(height, $(window).get(0).innerHeight / 2);
drawImage();
};

function drawImage() {
//shadow
context.shadowBlur = 20;
context.shadowColor = rgb(0,0,0);

//image
var image = new Image();
image.src = http://www.netstate.com/states/maps/images/ca_outline.gif;
$(image).load(function () {
image.height = canvas.height();
image.width = canvas.width();
context.drawImage(image);
});
};


Is there a solution to making the canvas responsive? Or do I just need to lock the canvas and image down to predefined sizes?


More From » css

 Answers
96

width and height of image are read-only so that won't work.



Try instead:



 context.drawImage(image, 0, 0, canvas.width, canvas.height);


This will draw the image the same dimension as the canvas is (you don't need to reload the image every time btw. - just load it once globally and reuse the image variable.)


[#73219] Saturday, January 11, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alejandro

Total Points: 231
Total Questions: 102
Total Answers: 107

Location: Jordan
Member since Wed, Jun 17, 2020
4 Years ago
alejandro questions
Mon, Jul 18, 22, 00:00, 2 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Thu, Sep 10, 20, 00:00, 4 Years ago
;