Canvas一般是指画布,最近对用html5写游戏比较感兴趣,所以简单的用了一下Canvas。

之前接触Canvas是在silverlight和wpf上用到过他,在silverlight上Canvas是一个绝对定位的容器,里面可以放任何控件。我们通过他可以构建画布、图形应用、GIS应用等。

在html5中,canvas是一个新增的标签:

<canvas></canvas>

他有基本的html标签的所有属性,一样可以给他设置style。

<canvas style="width:400px;height:300px;"></canvas>

<style>
canvas{width:400px;height:400px;background:#000;}
</style>
<canvas></canvas>

他还有一个特定的attribute:

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

这里的height、width与以往的html标签的attribute不同,也与style中的height、width不同,这里主要是指canvas中的坐标范围。而style里的width、height是指canvas实际展示的大小。

比如定义下面的一个canvas:

<canvas width="400" height="300" style="width:600px;height:450px;border:1px solid #000;"></canvas>

然后在canvas中画一个坐标为  100、50,大小为200、150的矩形,你会看到实际的效果如下图:

html5的Canvas

图中 canvas的大小是通过style决定的 600px * 450px,但是填满整个canvas的坐标只是400*300, 对应着括号里的大小。

在canvas中画图是基于坐标的,所以100, 50的坐标转化成了150px,75px的屏幕坐标,矩形的大小也由200*150转换成300px*225px的屏幕大小。

你可以按照下面的代码自己试一试:

<!doctype html>
<html>

<body>
<canvas width="400" height="300" style="width:600px;height:450px;border:1px solid #000;"></canvas>
<script>
var context =document.getElementsByTagName("canvas")[0].getContext("2d");
context.fillRect(100,50,200,150);
</script>
</body>
</html>
View Code

相关文章:

  • 2021-06-12
  • 2021-11-27
  • 2021-10-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-07-27
  • 2021-08-18
  • 2021-09-23
  • 2021-10-05
  • 2022-02-26
相关资源
相似解决方案