Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

javascript - Make Html5 Canvas and Its contained image responsive across browsers

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...