canvas标签的width和height以及style.width和style.height的区别

简介:

背景

  今天在博问中看到一个问题:用canvas 的 lineto方法画对角线,但画出来的图形不对?

  这是一个很常见的误区,这里给大家细说一下。

原理

  在w3网站上是这样解释的:

The canvas element has two attributes to control the size of the coordinate space: width and height. These attributes, when specified, must have values that are valid non-negative integersThe rules for parsing non-negative integers must be used to obtain their numeric values. If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead. The width attribute defaults to 300, and the height attribute defaults to 150.

The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.

  其实这里已经说的很明白,通俗点说就是在canvas中定义width、height跟在style中定义width和height是不同的,canvas标签的width和height是画布实际宽度和高度,绘制的图形都是在这个上面。而style的width和height是canvas在浏览器中被渲染的高度和宽度。如果canvas的width和height没指定或值不正确,就被设置成默认值(width:300px,height:150px)。

  我们可以利用style的width和height来缩放canvas,请看下面的示例。

示例

  示例代码如下:

<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function drawDiagonal(id){
var canvas=document.getElementById(id);
var context=canvas.getContext("2d");
context.beginPath();
context.moveTo(
0,0);
context.lineTo(
100,100);
context.stroke();
}

window.onload
=function(){
drawDiagonal(
"diagonal1");
drawDiagonal(
"diagonal2");
drawDiagonal(
"diagonal3");
}
</script>
</head>
<body>
<canvas id="diagonal1" style="border:1px solid;" width="100px" height="100px"></canvas>
<canvas id="diagonal2" style="border:1px solid;width:200px;height:200px;" width="100px" height="100px"></canvas>
<canvas id="diagonal3" style="border:1px solid;width:200px;height:200px;"></canvas>
</body>
</html>



本文转自Artwl博客园博客,原文链接:http://www.cnblogs.com/artwl/,如需转载请自行联系原作者

相关文章
|
2月前
|
XML 存储 编解码
svg的viewBox、width和height的设置说明
svg的是没有边界的,svg画布只是用于展示svg世界中某一个范围的内容,而对于超过了svg画布范围的内容,则会被遮挡。默认svg画布默认显示世界坐标下原点坐标的width*height面积的矩形视野。
|
4月前
|
前端开发
line-height与height的区别
line-height与height的区别
20 0
|
8月前
|
JavaScript
jQuery width()、height()
jQuery width()、height()
19 0
IE6下面,为什么不能设置height:1px的元素
在用DIV构建网页的时候,有时候需要的高度很小,这时候就可能会出现问题,因为,IE6下DIV有个默认的高度,大约10-12px。当你试图定义一个高度小于这个默认值的 div 的时候, IE 会固执的认为这个层的高度不应该小于字体的行高。
53 0
|
Web App开发 前端开发
给Img标签设置height和width属性
给Img标签设置height和width属性
525 0
html+css实战94-内容width和height
html+css实战94-内容width和height
75 0
html+css实战94-内容width和height
|
前端开发
CSS - 行内元素的 padding、margin、width、height、line-height 是否无效?
CSS - 行内元素的 padding、margin、width、height、line-height 是否无效?
393 0
CSS - 行内元素的 padding、margin、width、height、line-height 是否无效?
|
JavaScript 前端开发