html5 canvas浅介(一)
来源:互联网 发布:snmp采集哪些数据 编辑:程序博客网 时间:2024/06/05 06:17
什么是canvas?
Canvas 通过JavaScript 来绘制2D图形。Canvas 是逐像素进行渲染的。开发者可以通过javascript脚本实现任意绘图。
在canvas 中,一旦图形被绘制完成,它就不会继续得到浏览器的关注。如果其位置发生变化,那么整个场景也需要重新绘制,包括任何或许已被图形覆盖的对象。
今天的目标很是简单,为了方便大家进军canvas,当然是不想打击大家信心,所以就以最最简单的画直线来画
<head><meta charset="UTF-8"><title></title><style>/*注意这里是实际的大小*/.canvas {width: 200px;height: 200px;border: 1px solid #000000;}</style></head><body><!--注意,canvas他的总长是300单位,是相对于内部的,而高度为150个单位--><canvas class="canvas" width="300" height="300"></canvas></body>
当然,最终的结局只是一块类似div的,有黑边的框框,因为我们什么都没做,这里需要科普一下,canvas的默认宽度是300,默认的高度是150,什么意思???难道不是代码中定义的200px吗???原文是这样解释的:
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 integers. The 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)。
这就会导致我们在画图形的时候会奇怪我们代码明明已经很是正确了,但是画出来的图形依旧是错误的
接下来我们开始写我们的js代码,这点也需要科普一下,就是我们操作canvas,实际上不是操作canvas,而是操作context
简单代码如下:
var c = document.querySelector(".canvas");var cxt = c.getContext("2d");cxt.moveTo(0, 0);cxt.lineTo(299, 149);cxt.stroke();
解析一下,首先我们获取了我们的画布,接下来,我们获取了我们真正要操作的对象,我们的context(“2d”)。。。为什么是2d,暂时大家不用理解,后面博客会讲
接着,我们把焦点移动到了原点,然后链接到了(299,149)的位置,注意,这两部没有画线,只有在执行下一步的ctx。stroke()的时候才是真正的画线了
就这样,一个简单的画直线就完成了
阅读全文
0 0
- html5 canvas浅介(一)
- html5 canvas 线(一)
- HTML5- Canvas入门(一)
- HTML5 canvas画布(一)
- HTML5 之 Canvas (一)
- 浅谈HTML5 canvas(一)
- HTML5之帆布(canvas)(一)
- HTML5之画布(canvas)(一)
- HTML5 Canvas绘制渐变(一)
- HTML5中的Canvas绘图操作(一)
- html5之canvas实例(一)
- HTML5 Canvas实现贪吃蛇(一)
- HTML5 Canvas 基础 一
- HTML5之Canvas(一)
- html5 canvas浅介(二)
- HTML5 Canvas实践(一)Canvas 基础知识
- HTML5----Canvas 学习笔记一
- html5 canvas元素使用(一)
- SQLite学习手册(内置函数)
- 字符串训练01—请编写一个C函数,该函数将一个字符串逆序
- jquery-1.12.4.intellisense.js 使用
- C++中的Vector
- 递归上层调用部分由于下层使用了return语句直接结束,无法累计所有的数据?
- html5 canvas浅介(一)
- go语言的命令行库
- Linux ubuntu 文件类型 权限
- MyBatis----多表查询返回包装类
- 原生JavaScript和JQuery两种方式实现AJAX
- A
- mysql小结常用知识点
- SQLite学习手册(索引和数据分析/清理)
- table表格中每行都有一个修改按钮怎么实现修改功能