Core Canvas–Day1

绘制

1.坐标系统:

canvas的坐标以左上角为原点,如图

Core Canvas–Day1

可对canvas的坐标系统进行变换,变换的方式有

  • 平移translate
  • 旋转rotate
  • 缩放scale
  • 创建自定义的变换方式,切变

2.矩形的绘制

API:

  • 清除:clearRect(double x , double y, double w,double h); //x,y是坐标位置,w,h是宽高
  • 描边:strokeRect(double x ,double y ,double w ,double h);

--------strokeStyle,lineWidth,lineJoin,miterLimit

  • 填充:fillRect(double x,double y,double w,double h);

示例:http://runjs.cn/code/ibcpa7fm

var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"); context.font = "14px Microsoft YaHei";
context.fillText("Click to Erase",200,15) context.fillStyle = "#bc223d";
context.fillRect(50,50,100,20); //context.lineJoin = "round";
context.lineWidth = 1;
context.strokeStyle = "green";
context.strokeRect(50,10,100,20); canvas.onmousedown = function(){
context.clearRect(0,0,canvas.width,canvas.height);
}

3.渐变色与图案

3.1渐变色

canvas支持线性渐变(linear)和放射渐变(radial)

API

方法

描述

CanvasGradient.createLinearGradient(double x0,double y0,double x1,double y1);

创建线性渐变;参数表示线性渐变的两个端点.返回CanvasGradient实例,可通过CanvasGradient.addColorStop()方法来向线性渐变增加颜色停止点.

CanvasGradient.createRadialGradient(double x0,double y0,double r0,double x1,double y1,double r1);

创建放射渐变.参数表示位于圆锥形变区域两端的圆形.返回CnvasGradient实例.

示例:http://runjs.cn/code/mdh08l1c

var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d");
var gradient = context.createLinearGradient(0,0,canvas.width,0);
gradient.addColorStop(0,"blue");
gradient.addColorStop(0.25,"#bc223d");
gradient.addColorStop(0.5,"#eaeaea");
gradient.addColorStop(0.75,"#bc223d");
gradient.addColorStop(1,"blue");
context.fillStyle = gradient;
//context.fillRect(0,0,canvas.width,canvas.height);
context.rect(0,0,canvas.width,canvas.height);
context.fill();
//2.放射渐变
var radialGradient = context.createRadialGradient(canvas.width/2,canvas.height,10,canvas.width/2,0,100);
radialGradient.addColorStop(0,"rgba(0,0,255,0.5)");
radialGradient.addColorStop(0.5,"rgba(255,0,255,0.9)");
radialGradient.addColorStop(1,"#bc223d");
context.fillStyle = radialGradient;
context.fillRect(0,0,canvas.width,canvas.height);

3.2 图案

  先上示例:http://runjs.cn/code/zzipqao3

API

方法

描述

CanvasPattern createPattern(HTMLImageElement | HTMLCanvasElement | HTMLVideoElement image,DOMString repetition)


第一个参数为指定的类型图案,第二个参数为如何重复该图案.值为repeat,no-repeat,repeat-x,repeat-y
上一篇:Luogu P1951 收费站_NOI导刊2009提高(2)


下一篇:JS函数的几种用法