[英]assign canvas to div, adapt canvas dimensions to div dimenson - how to fix?
我有一個以div為背景的畫布示例(我從另一個示例中派生了它,不記得在哪里找到它了): http : //jsfiddle.net/sevku/6jace59t/18/
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');
var divHeight = document.getElementById('canvas').clientHeight;
var divWidth = document.getElementById('canvas').clientWidth;
function assignToDiv(){ // this kind of function you are looking for
dataUrl = canvas.toDataURL();
document.getElementsByTagName('div')[0].style.background='url('+dataUrl+')'
}
function draw() { // replace with your logic
ctx.fillStyle = "rgb(100, 250, 100)";
ctx.fillRect (10, 10, divWidth-20, divHeight-20);
}
draw()
assignToDiv()
我的問題; 如果我將div的尺寸設置為300 x 150,則畫布會執行應做的工作。 但是,如果我更改尺寸,則畫布應該適合div尺寸。 我沒有做錯什么錯了?
PS:我是初學者,所以請原諒我愚蠢的問題。
這是因為如果您不指定canvas的 width
和height
,則默認為300x150
,因此在從div獲取寬度和高度后,還應該使用它們來設置canvas
的尺寸。
值得注意的另一點是,您使用div.style.background
屬性設置背景圖像,但是,因為背景相關的屬性很多(例如:jsfiddle中的background-repeat
, background-position
, background-size
...), background
可以一次設置所有這些。 當您使用div.style.background='url('+dataUrl+')';
。 它將所有其他與背景相關的屬性覆蓋為initial
。
如果要保留這些屬性,則可以在設置style.background
之后重置它們,也可以使用div.style.backgroundImage
更改背景圖像,而不影響其他與背景相關的屬性。
var canvas = document.getElementsByTagName('canvas')[0]; var ctx = canvas.getContext('2d'); var divHeight = document.getElementById('canvas').clientHeight; var divWidth = document.getElementById('canvas').clientWidth; // VVVV After you get WxH, set the canvas's dimension too. canvas.width = divWidth; canvas.height = divWidth; var div1 = document.getElementById('canvas'); var div2 = document.getElementById('canvas2'); function assignToDiv(div){ // this kind of function you are looking for var dataUrl = canvas.toDataURL(); div.style.background='url('+dataUrl+')'; // This line will overwrite your background settings. div.style.backgroundRepeat = 'repeat-x'; // Use this to set background related properties after above. } function assignToDivAlt(div){ // this kind of function you are looking for var dataUrl = canvas.toDataURL(); div.style.backgroundImage = 'url('+dataUrl+')'; // Only set the background-image would have same effect. } function draw() { // replace with your logic ctx.fillStyle = "rgb(100, 250, 100)"; // If you don't set WH, then the canvas would be 300x150, and those // you drawed but out of boundary are clipped. ctx.fillRect (10, 10, divWidth-20, divHeight-20); } draw() assignToDiv(div1); assignToDiv(div2);
canvas {display:none;} div { width:600px; height:550px; border:1px solid grey; background-repeat:repeat-x; }
<canvas></canvas> <div id="canvas"></div> <div id="canvas2"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.