将CSS调整大小属性添加到Canvas元素 [英] Add CSS Resize Property to Canvas Element

查看:244
本文介绍了将CSS调整大小属性添加到Canvas元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CSS resize属性可以应用于画布元素吗?使用 MDN文档作为参考,该aribrary元素示例

Can the CSS resize property be applied to canvas elements? Using the MDN document as a reference, the aribrary element example doesn't seem to work with canvas as the element.

HTML

<canvas width=300 height=300></canvas>

CSS

canvas {
  resize: both;
  overflow: hidden;
  border: 1px solid black;
}

我创建了一个jsfiddle与其他一些我遇到的问题碰到:
https://jsfiddle.net/m540fevj/1/

I've created a jsfiddle with some other cases of the issues I've run into: https://jsfiddle.net/m540fevj/1/

在Chrome中,第一个canvas元素显示了应用于它的resize属性,但由于它实际上不能调整大小,因此显示不正确。第二个元素显示,只有一个像素差异,该元素的可调整大小性消失了。第三个元素表明,不对其进行绘制,它似乎也不会应用该属性。 div元素显示了我最终希望canvas元素的外观。在Firefox中,除了div以外,其他任何东西都不能调整大小。

In Chrome the first canvas element shows the resize property being applied to it, but not properly since it's not actually resizable. The second element shows that with a one pixel difference the resizableness of the element disappears. The third element shows that without drawing to it, it also doesn't appear to apply the property. The div element shows what I ultimately want the canvas element to look like. In Firefox, nothing but the div is resizable.

问题是由于canvas元素处理CSS宽度和高度的方式的唯一性引起的吗? b

Is the issue due to the uniqueness of how the canvas element handles CSS width and height?

推荐答案

否, CSS 调整大小 不适用于内联元素。 < canvas> ,就像< img> 是内联元素一样。因此,您不能在画布上使用此属性。 请参阅MDN说明

No, CSS resize is not applicable to inline elements. <canvas>, just like <img> is an inline element. Thus, you cannot use this property on canvases. See MDN Note

请注意,您可以将画布包装在可调整大小的块容器中,并使画布以100%的比例显示,但是请记住,这只是用于显示。这样会拉伸画布图像的实际像素内容。

Note that you could wrap you canvas inside a resizeable block container and make your canvas to display at 100%, but remember this is just for display. This will stretch the actual pixel content of your canvas image.

const ctx = canvas.getContext('2d');
ctx.arc(25,25,25,0,Math.PI*2);
ctx.fill();

.resize-me {
  display: inline-block;
  border: 1px solid;
  resize: both;
  width: 50px;
  height: 50px;
  overflow: hidden;
}
canvas {
  width: 100%;
  height: 100%;
  pointer-events: none; /* Chrome needs this oO */
}

<div class="resize-me">
  <canvas id="canvas" width="50" height="50"></canvas>
</div>

这篇关于将CSS调整大小属性添加到Canvas元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆