简体   繁体   English

使Html5 Canvas及其包含的图像在浏览器中响应

[英]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. 我有一个canvas对象,我想为Web应用程序添加一个图像。 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. 我可以加载图像,但我遇到了两个问题:图像不会延伸到画布,并且画布不会延伸到任何浏览器中的整个div,而是Firefox。

http://jsfiddle.net/LFJ59/1/ 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? 或者我只需要将画布和图像锁定到预定义的大小?

width and height of image are read-only so that won't work. 图像的widthheight是只读的,因此不起作用。

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.) 这将绘制与画布相同尺寸的图像(每次btw都不需要重新加载图像。 - 只需将其加载一次全局并重新使用image变量。)

<canvas id="imageView" width="1000" height="1000" style="width:100%; height:100%"></canvas>

Both CSS and height and width attributes can be used and do not need to agree in size. 可以使用CSS和高度和宽度属性,并且不需要在大小上达成一致。 The CSS style will determine the displayed size, you asked for a canvas that can stretch. CSS样式将决定显示的大小,您要求可以拉伸的画布。 The width and height control the number of pixels the canvas uses for drawing. 宽度和高度控制画布用于绘制的像素数。

for example this will be scaled 10 to 1, and with anti-aliasing scrolling an drawing in this canvas would be as smooth as silk. 例如,这将缩放为10比1,并且通过抗锯齿滚动,此画布中的绘图将像丝绸一样平滑。

<canvas id="imageView" width="1000" height="1000" style="width:100px; height:100px"></canvas>

If CSS is not used, their defaults will be the width and height attributes of the canvas element. 如果未使用CSS,则它们的默认值将是canvas元素的width和height属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM