html5 canvas-1.canvas介绍(hello canvas)

2019-01-28 19:37:33王冬梅

不过推荐大家使用modernizr.js库完成这一工作,这是一个很通过的html5 js库,提供了很多有用的方法

复制代码

function canvasSupport () {
return Modernizr.canvas;
}

canvas支持2d渲染,通过如下代码实现:
var context = theCanvas.getContext("2d");
下面我们就可以通过context对象在canvas上绘制图像了。

复制代码

//设置区域颜色
context.fillStyle = "#ffffaa";
//绘制区域
context.fillRect(0, 0, 500, 300);
//设置字体
context.font = "20px _sans";
//设置垂直对齐方式
context.textBaseline = "top";
//绘制文字
context.fillText ("Hello World!", 195, 80);
//设置边框颜色
context.strokeStyle = "#000000";
//绘制边框
context.strokeRect(5, 5, 490, 290);

下面介绍下图片的绘制。由于图片的异步下载的,为了保证你用canvas绘制一个图片时,该图片已经下载完毕,我们使用下面的方式:

复制代码

var helloWorldImage = new Image();
helloWorldImage.src = "helloworld.gif";
helloWorldImage.onload = function () {
context.drawImage(helloWorldImage, 160, 130);
}

当图片下面完毕时,会触发onload事件,这里再使用context对象绘制图片。
大家下载demo看完整代码,demo下载地址:html5canvas.helloworld.zip