Html5 Canvas 使用

<div>

    <img id="scream" src="dali.jpg" alt="The Scream" width="120" height="80">
    <br>
    <canvas id="myCanvas" width="400" height="400" style="border:1px solid #000000;">
      你的浏览器不支持 canvas,请升级你的浏览器。
    </canvas>
    <br>

  </div>

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

/*
  beginPath(): 新建一条路径,路径一旦创建成功,图形绘制命令被指向到路径上生成路径
  moveTo(x, y): 把画笔移动到指定的坐标(x, y)。相当于设置路径的起始点坐标。
  closePath(): 闭合路径之后,图形绘制命令又重新指向到上下文中
  stroke(): 通过线条来绘制图形轮廓
  fill(): 通过填充路径的内容区域生成实心的图形
*/


// 画矩形
// fillRect(x,y,width,height) 方法定义了矩形当前的填充方式。
ctx.fillStyle = "#ccc";
ctx.fillRect(0, 0, 100, 50);



// 画直线
// moveTo(x,y) 定义线条开始坐标;lineTo(x,y) 定义线条结束坐标
// 定义开始坐标(0,0), 和结束坐标 (200,100)。然后使用 stroke() 方法来绘制线条:
ctx.moveTo(95, 50);
ctx.lineTo(200, 100);
ctx.stroke();


// 画园 arc(x,y,r,start,stop)
ctx.beginPath();
ctx.arc(300, 300, 40, 0, 2 * Math.PI);  //  圆心(95,50),半径40, 起点:0
ctx.stroke();


// 文本
// font - 定义字体
// fillText(text,x,y) - 在 canvas 上绘制实心的文本
// strokeText(text,x,y) - 在 canvas 上绘制空心的文本

ctx.font = "30px Arial";
ctx.fillStyle = "#555";
ctx.fillText("Hello World", 10, 120);
ctx.strokeText("Hello World", 10, 150);


// 渐变
// 以下有两种不同的方式来设置Canvas渐变:
//     createLinearGradient(x,y,x1,y1) - 创建线条渐变
//     createRadialGradient(x,y,r,x1,y1,r1) - 创建一个径向/圆渐变
// addColorStop()方法指定颜色停止,参数使用坐标来描述,可以是0至1.
// 使用渐变,设置fillStyle或strokeStyle的值为 渐变,然后绘制形状,如矩形,文本,或一条线。

// 创建渐变
var grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");
// 填充渐变
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);



// 图像
// 把一幅图像放置到画布上, 使用以下方法: drawImage(image, x, y, width, height)

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
img.onload = function () {
  ctx.drawImage(img, 200, 200, 100, 50);
}

// 图像切片
// drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
//     第一个参数和其它的是相同的,都是一个图像或者另一个 canvas 的引用。
//     其他 8 个参数:
//     前 4 个是定义图像源的切片位置和大小,后 4 个则是定义切片的目标显示位置和大小。
//     注意:后四个相当于drawImage(image, x, y, width, height)中的x, y, width, height

img.onload = function () {
  ctx.drawImage(img, 30, 30, 400, 600, 200, 200, 100, 50);
}
 

猜你喜欢

转载自www.cnblogs.com/cckui/p/12377330.html