- WHAT: canvas 是什么?
canvas 是画布,也就是一块矩形区域。 WHY: canvas 作用是什么?
用它画图像。测试内容:
- 画 矩形
- 画三角形
- 画圆
- 画线性渐变矩形
- 画图片
示例代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test html5 canvas</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px red solid"></canvas>
<div style="display:none">
<img id="img" src = '../images/psuCA0V6ZG5.jpg'>
</div>
<script>
function createCanvas(){
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// stroke rectangle
// strokeRect(context);
// stroke line
// strokeLine(ctx);
// stroke arc
// strokeArc(ctx);
// stroke linear gradient
// strokeLinearGradient(ctx);
drawImage(ctx);
}
function strokeRect(ctx){
context.fillStyle="red";
context.fillRect(0,0,280,90);
}
function strokeLine(ctx){
ctx.moveTo(100, 100);
ctx.lineTo(500,400);
ctx.lineTo(100,400);
ctx.lineTo(100, 100);
ctx.stroke();
}
function strokeArc(ctx){
ctx.fillStyle="red";
ctx.beginPath();
ctx.arc(200,200,100,0, 2*Math.PI, false);
ctx.closePath();
ctx.fill();
}
function strokeLinearGradient(ctx){
var clg = ctx.createLinearGradient(100,100, 300,100);
clg.addColorStop(0, "red");
clg.addColorStop(1, "cyan");
ctx.fillStyle = clg;
ctx.fillRect(100,100, 300,200);
}
function drawImage(ctx){
// var img = new Image();
// img.src = "../images/psuCA0V6ZG5.jpg";
// ctx.drawImage(img,0,0);
var img2 = document.getElementById("img");
ctx.drawImage(img2,0,0);
}
window.onload = createCanvas;
</script>
</body>
</html>