javascript - Setting canvas 'width/height' in CSS results in surprising behavior -


i have 2 html canvas elements, , i've drawn lines on them.

the 2 canvases identical except in 1 have specified width , height using tag attributes (canvas-1), , in other 1 have specified width , height in css (canvas-2).

i've found when log width , height (i in drawdividers below), height canvas-2 150 instead of 300 have expected. find surprising height wrong, lines drawn have expected them, except blurry. going on here? there simple mental model adopt of html/css/canvas explain this?

i on chrome in windows in case relevant.

pic of 2 canvases

demo here: codepen link

html

<canvas id="canvas-1" class="outlined" width=300 height=300></canvas> <span> __ </span> <canvas id="canvas-2" class="outlined"></canvas> 

css

#canvas-1 {   outline-style: solid; } #canvas-2 {   width: 300px;   height: 300px;   outline-style: solid; } 

javascript

function drawdividers(eid) {   var canvas = document.getelementbyid(eid);   var width = canvas.width;   var height = canvas.height;   console.log(eid, width, height);   var ctx = canvas.getcontext('2d');   ctx.linewidth = 1;   (var = 1; <= 2; i++) {     ctx.moveto(i*width/3, 0.1*height);     ctx.lineto(i*width/3, 0.9*height);     ctx.stroke();     ctx.moveto(0.1*width, i*height/3);     ctx.lineto(0.9*width, i*height/3);     ctx.stroke();   } }  drawdividers('canvas-1'); drawdividers('canvas-2'); 

this what's happening:

a canvas has default width of 300 pixels , height of 150 pixels.

when don't set them explicitly in markup, javascript lines

var width = canvas.width; var height = canvas.height; 

return default 300 , 150 respectively.

so drawing done in area of 300x150 pixels, , css resizes canvas 300x300, , blurring happens because of that. (like when sizing picture beyond original size, blurring happens.)