javascript 使 Html5 Canvas 及其包含的图像跨浏览器响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21083183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make Html5 Canvas and Its contained image responsive across browsers
提问by ChargerIIC
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.
我有一个画布对象,我想将图像放入 Web 应用程序。我可以加载图像,但我遇到了两个问题:图像不会拉伸到画布,并且画布不会拉伸以覆盖除 Firefox 之外的任何浏览器中的整个 div。
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?
是否有使画布响应的解决方案?或者我只需要将画布和图像锁定到预定义的大小?
回答by
width
and height
of image are read-only so that won't work.
width
和height
图像是只读的,所以不起作用。
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.)
这将绘制与画布相同尺寸的图像(顺便说一句,您不需要每次都重新加载图像。 - 只需全局加载一次并重用image
变量。)
回答by Wayne
<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. The CSS style will determine the displayed size, you asked for a canvas that can stretch. The width and height control the number of pixels the canvas uses for drawing.
CSS 和 height 和 width 属性都可以使用,不需要大小一致。CSS 样式将决定显示的大小,您要求可以拉伸的画布。宽度和高度控制画布用于绘图的像素数。
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 元素的宽度和高度属性。